ruby-on-railsrubyrails-activerecord

Saving an associated polymorphic object duplicates it


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.


Solution

  • 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.