store_model icon indicating copy to clipboard operation
store_model copied to clipboard

Nested forms not working when using accepts_nested_attributes_for

Open acetinick opened this issue 4 years ago • 7 comments

Hi I am having issues when trying to update settings using fields_for nested attributes in forms. Below the the following way i am trying to implement it based on the comments in read in the PR

in view

 <%= form_for @tenant, url: settings_authentications_url(), method: :put do |f| %>
      <%= render 'shared/error_messages', object: @tenant.settings %>

      <%= f.fields_for :settings do |o| %>
          ...
      <% end %>
  <% end %>
class Tenant
  attribute :settings, TenantConfiguration.to_type
  validates :settings, store_model: true
  accepts_nested_attributes_for :settings
end
class TenantConfiguration
  include StoreModel::Model

  accepts_nested_attributes_for :settings
end

image

acetinick avatar Feb 01 '21 21:02 acetinick

In order for me to resolve this for now, i just put this in my model

attribute :settings, TenantConfiguration.to_type
validates :settings, store_model: true

def settings_attributes=(values)
  self.settings.assign_attributes( values)
end

acetinick avatar Feb 01 '21 21:02 acetinick

Hi @acetinick! Could you please remove the line accepts_nested_attributes_for :settings from TenantConfiguration and try again?

DmitryTsepelev avatar Feb 02 '21 14:02 DmitryTsepelev

for an ActiveRecord model, I had to do a similar thing to allow nested attributes from the controller.

class Model
  def configuration_attributes=(config)
    self.configuration = config
  end
end

sairam avatar Feb 09 '21 11:02 sairam

Seeing a similar thing.

class Listing < ActiveRecord::Base
    attribute :properties, ListingProperties.to_type
    validates :properties, store_model: true
    accepts_nested_attributes_for :properties

ArgumentError (No association found for name properties'. Has it been defined yet?):`

Which according to the docs here: https://github.com/DmitryTsepelev/store_model/blob/master/docs/nested_models.md should work?

sevenseacat avatar Feb 24 '21 04:02 sevenseacat

Hi @sevenseacat! Looks like you're calling accepts_nested_attributes_for from your parent class, while it was designed to handle situations, when one nested model is inside another one 🙂

DmitryTsepelev avatar Feb 24 '21 06:02 DmitryTsepelev

@sevenseacat see https://github.com/DmitryTsepelev/store_model/issues/85#issuecomment-775867184

sairam avatar Feb 24 '21 06:02 sairam

ah hah I misread the documentation then :) cheers!

(but I think this is what the OP was trying to do as well)

sevenseacat avatar Feb 24 '21 06:02 sevenseacat