2

Rails 7 adds accepts_nested_attributes_for support for delegated_type

 2 years ago
source link: https://blog.saeloun.com/2022/02/02/rails-7-adds-nested-attributes-for-delegated-type
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK