DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.04k stars 85 forks source link

Use accepts_nested_attributes_for with StoreModel::NestedAttributes #152

Closed morgangrubb closed 1 year ago

morgangrubb commented 1 year ago

This makes it possible to use the complete Rails pathway for nested form objects.

Also updates accepts_nested_attributes_for to allow the Rails-syntax.

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.new(supplier_params)
  @supplier.save
end

private

def supplier_params
  params.require(:supplier).permit(products_attributes: [:name])
end
morgangrubb commented 1 year ago

Based on 1.6.2 since the json-as-string 2.x versions break our application.

morgangrubb commented 1 year ago

LGTM, could you please take a look at that rubocop issue? Also, this is not gonna be a breaking change, right?

Absolutely, I'll get that done today.

As for it being a breaking change, I don't think it can be? No functionality is added to the ActiveRecord model unless you include StoreModel::NestedAttributes (I debated doing that automatically but figured we're probably better off making it a deliberate thing) and the change to the attribute getter/setter detection from Types::Many to Types::ManyBase is just so that Many and ManyPolymorphic are both handled.

Other than those changes, everything is exactly as it was in 1.6.2 so I think it's pretty safe.

The other thing I am debating doing is supporting reject_if as per Rails accepts_nested_attributes_for.

morgangrubb commented 1 year ago

Any chance we could get this released as 1.6.3 while waiting for the stringified json in 2.x to get resolved?