Work with JSON-backed attributes as ActiveRecord-ish models
Work with JSON-backed attributes as ActiveRecord-ish models
StoreModel gem allows you to wrap JSON-backed DB columns with ActiveModel-like classes.
class Configuration
include StoreModel::Model
attribute :model, :string
enum :status, %i[active archived], default: :active
validates :model, :status, presence: true
end
class Product Read more about the motivation in the [Wrapping JSON-based ActiveRecord attributes with classes](https://evilmartians.com/chronicles/wrapping-json-based-active-record-attributes-with-classes) post
## Getting started
Start with creating a class for representing the hash as an object:
```ruby
class Configuration
include StoreModel::Model
attribute :model, :string
attribute :color, :string
endAttributes should be defined using Rails Attributes API. There is a number of types available out of the box, and you can always extend the type system.
Register the field in the ActiveRecord model class:
class Product
Resulting in:
In the controller:
def create
@supplier = Supplier.from_value(supplier_params)
@supplier.save
end
private
def supplier_params
params.require(:supplier).permit(products_attributes: [:name])
endIf you're using ActiveAdmin, enable compatibility mode to make the has_many form helper work with StoreModel attributes:
# config/initializers/store_model.rb
StoreModel.config.active_admin_compatibility = trueExample usage:
# app/models/supplier.rb
class Supplier
include StoreModel::Model
attribute :title, :string
attribute :address, :string
end
# app/models/product.rb
class Product < ApplicationRecord
include StoreModel::NestedAttributes
attribute :suppliers, Supplier.to_array_type
accepts_nested_attributes_for :suppliers, allow_destroy: true
end
# app/admin/products.rb
ActiveAdmin.register Product do
permit_params suppliers_attributes: [:title, :address, :_destroy]
form do |f|
f.has_many :suppliers, allow_destroy: true do |s|
s.input :title
s.input :address
end
f.actions
end
endStoreModel::Model API:Initially sponsored by Evil Martians.
The gem is available as open source under the terms of the MIT License.
No open issues yet, or sync has not completed.