Skip to content

Add accepts_nested_attributes_for support for delegated_type#2

Open
cspetterson wants to merge 1 commit intorobertomiranda:masterfrom
zapnito:master
Open

Add accepts_nested_attributes_for support for delegated_type#2
cspetterson wants to merge 1 commit intorobertomiranda:masterfrom
zapnito:master

Conversation

@cspetterson
Copy link

Previously, trying to use nested attributes would raise an error when trying to build polymorphic associations:

Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
# ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?

Adding this, matches the rails core implementation and prevents using have to add build_#{role} methods every time we introduce a nested association, which was a suggestion on Stack Overflow (https://stackoverflow.com/a/45306832), eg:

def build_attachable(params)
  self.attachable = attachable_type.constantize.new(params)
end

The pull request first appeared in v7.0.0.rc1, here: https://github.com/rails/rails/pull/41717/files

We've since forked this and using it in our app at Zapnito

From the original PR:

Summary

This PR adds nested_attributes_for support to delegated_type, this allows a developer to create and update records easily without needing to write specific methods like:

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]

  def self.create_with_comment(content, creator: Current.user)
    create! entryable: Comment.new(content: content), creator: creator
  end
end

Using nested_attributes_for allows to execute the following:

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]
  accepts_nested_attributes_for :entryable
end

params = { entry: { entryable_type: 'Comment', entryable_attributes: { content: 'Smiling' } } }
entry = Entry.create(params[:entry])

Why

Nested forms based on accepts_nested_attributes_for are very powerful and this is the last piece missing to also be able to use it on Delegated Types.

Question

Since this is a polymorphic belongs_to relationship, what other tests would we like to have? As it is already tested in TestNestedAttributesOnABelongsToAssociation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant