Rails 7 adds accepts_nested_attributes_for support for delegated_type


Rails 6.1 added delegated_type which resembles polymorphic relations. Using delegated_type the developer is introduced with a bunch of useful methods and scopes. Checkout this PR to know more about this feature.

Before

For the sake of understanding, let’s consider the following declaration of the Note model.

# app/models/notes.rb
class Note < ApplicationRecord
  delegated_type :authorable, types: %w[ Customer Employee ]
end

# app/models/employee.rb
class Employee < ApplicationRecord
end

Previously, in order to create a new delegated_type record, we would do something like this:

emp_one = Employee.create!(name: "emp one")
Note.create!(authorable: emp_one, body: "sample text")

If we try to save the note using nested attributes, it will raise an error:

params = { note: { authorable_type: 'Employee', body: "sample text", authorable_attributes: { name: 'Emp one' } } }

Note.create!(params[:note])
# ArgumentError: Cannot build association `authorable'. Are you trying to build a polymorphic one-to-one association?

After

With Rails 7 adding support of accepts_nested_attributes_for for delegated_type we can save the records as follows:

# app/models/notes.rb
class Note < ApplicationRecord
  delegated_type :authorable, types: %w[ Customer Employee ]

  accepts_nested_attributes_for :authorable
end
params = { note: { authorable_type: 'Employee', body: "sample text", authorable_attributes: { name: 'Emp one' } } }
note = Note.create!(params[:note])

To know more about this feature, checkout this PR.

Join Our Newsletter