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 < ApplicationRecord
attribute :configuration, Configuration.to_type
end
Working on a complex Rails application and need an experienced eye? I'm available for consulting — get in touch.
Imagine that you have a model Product with a jsonb column called configuration. This is how you likely gonna work with this column:
product = Product.find(params[:id])
if product.configuration["model"] == "spaceship"
product.configuration["color"] = "red"
end
product.save
This approach works fine when you don't have a lot of keys with logic around them and just read the data. However, when you start working with that data more intensively–you may find the code a bit verbose and error-prone.
For instance, try to find a way to validate :model value to be required. Despite of the fact, that you'll have to write this validation by hand, it violates the single-responsibility principle: why parent model (Product) should know about the logic related to a child (Configuration)?
📖 Read more about the motivation in the Wrapping JSON-based ActiveRecord attributes with classes post
Start with creating a class for representing the hash as an object:
class Configuration
include StoreModel::Model
attribute :model, :string
attribute :color, :string
end
Attributes 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 < ApplicationRecord
attribute :configuration, Configuration.to_type
end
When you're done, the initial snippet could be rewritten in the following way:
product = Product.find(params[:id])
if product.configuration.model == "spaceship"
product.configuration.color = "red"
end
product.save
Usage note: Rails and assigning Arrays/Hashes to records
self.my_stored_models = my_stored_models.map(&:as_json)) or by will_change! (self.my_stored_models_will_change!)StoreModel::NestedAttributes into your model will allow you to use accepts_nested_attributes_for in the same way as ActiveRecord.class Supplier < ActiveRecord::Base
include StoreModel::NestedAttributes
has_many :bicycles, dependent: :destroy
attribute :products, Product.to_array_type
accepts_nested_attributes_for :bicycles, :products, allow_destroy: true
end
This will allow the form builders to work their magic:
<%= form_with model: @supplier do |form| %>
<%= form.fields_for :products do |product_fields| %>
<%= product_fields.text_field :name %>
<% end %>
<% end %>
Resulting in:
<input type="text" name="supplier[products_attributes][0][name]" id="supplier_products_attributes_0_name">
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])
end
If 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 = true
Example 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
end
StoreModel::Model API:Initially sponsored by Evil Martians.
The gem is available as open source under the terms of the MIT License.
(top 30 of 61)
Ruby
100.0%
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 < ApplicationRecord
attribute :configuration, Configuration.to_type
end
Working on a complex Rails application and need an experienced eye? I'm available for consulting — get in touch.
Imagine that you have a model Product with a jsonb column called configuration. This is how you likely gonna work with this column:
product = Product.find(params[:id])
if product.configuration["model"] == "spaceship"
product.configuration["color"] = "red"
end
product.save
This approach works fine when you don't have a lot of keys with logic around them and just read the data. However, when you start working with that data more intensively–you may find the code a bit verbose and error-prone.
For instance, try to find a way to validate :model value to be required. Despite of the fact, that you'll have to write this validation by hand, it violates the single-responsibility principle: why parent model (Product) should know about the logic related to a child (Configuration)?
📖 Read more about the motivation in the Wrapping JSON-based ActiveRecord attributes with classes post
Start with creating a class for representing the hash as an object:
class Configuration
include StoreModel::Model
attribute :model, :string
attribute :color, :string
end
Attributes 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 < ApplicationRecord
attribute :configuration, Configuration.to_type
end
When you're done, the initial snippet could be rewritten in the following way:
product = Product.find(params[:id])
if product.configuration.model == "spaceship"
product.configuration.color = "red"
end
product.save
Usage note: Rails and assigning Arrays/Hashes to records
self.my_stored_models = my_stored_models.map(&:as_json)) or by will_change! (self.my_stored_models_will_change!)StoreModel::NestedAttributes into your model will allow you to use accepts_nested_attributes_for in the same way as ActiveRecord.class Supplier < ActiveRecord::Base
include StoreModel::NestedAttributes
has_many :bicycles, dependent: :destroy
attribute :products, Product.to_array_type
accepts_nested_attributes_for :bicycles, :products, allow_destroy: true
end
This will allow the form builders to work their magic:
<%= form_with model: @supplier do |form| %>
<%= form.fields_for :products do |product_fields| %>
<%= product_fields.text_field :name %>
<% end %>
<% end %>
Resulting in:
<input type="text" name="supplier[products_attributes][0][name]" id="supplier_products_attributes_0_name">
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])
end
If 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 = true
Example 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
end
StoreModel::Model API:Initially sponsored by Evil Martians.
The gem is available as open source under the terms of the MIT License.
(top 30 of 61)
Ruby
100.0%