Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add accepts_nested_attributes_for support for delegated_type #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions lib/delegated_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,21 @@ module ActiveRecord
# end
#
# Now you can list a bunch of entries, call +Entry#title+, and polymorphism will provide you with the answer.
#
# == Nested Attributes
#
# Enabling nested attributes on a delegated_type association allows you to
# create the entry and message in one go:
#
# class Entry < ApplicationRecord
# delegated_type :entryable, types: %w[ Message Comment ]
# accepts_nested_attributes_for :entryable
# end
#
# params = { entry: { entryable_type: 'Message', entryable_attributes: { subject: 'Smiling' } } }
# entry = Entry.create(params[:entry])
# entry.entryable.id # => 2
# entry.entryable.subject # => 'Smiling'
module DelegatedType
# Defines this as a class that'll delegate its type for the passed +role+ to the class references in +types+.
# That'll create a polymorphic +belongs_to+ relationship to that +role+, and it'll add all the delegated
Expand Down Expand Up @@ -186,6 +201,10 @@ def define_delegated_type_methods(role, types:)
public_send("#{role}_class").model_name.singular.inquiry
end

define_method "build_#{role}" do |*params|
public_send("#{role}=", public_send("#{role}_class").new(*params))
end

types.each do |type|
scope_name = type.tableize.gsub("/", "_")
singular = scope_name.singularize
Expand Down