1

I have two models, one of them being polymorphic and second one being a "parent" one:

class Person
  has_one :asset, as: :assetable
  accepts_nested_attributes_for :asset
end

class Asset
  belongs_to :assetable, class_name: Asset.name, polymorphic: true
end

And after saving a following form:

<% form_with model: @person do |f| %>
  <% f.fields_for :asset do |ff| %>
    <%= ff.text_field :name %>
  <% end %>
<% end %>

The associated Asset object is not being updated but, instead, a new copy of Asset is being created with given name and is being reassigned to the Person object. Why is that happening and how can i make that properly?

I'm on Rails 7.1.3 and Asset uses STI if that changes anything.

1

1 Answer 1

1

You should set update_only: true parameter for accepts_nested_attributes_for declaration:

accepts_nested_attributes_for :asset, update_only: true

Otherwise since you don't pass asset's ID in the form it creates a new one instead of updating the already existing one.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I temporarily resolved it by allowing id in permitted params which was far from ideal but i never head of that update_only setting and now it works like charm. Thank you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.