diff --git a/lib/delegated_type.rb b/lib/delegated_type.rb index a7dcfc3..b3c6d64 100644 --- a/lib/delegated_type.rb +++ b/lib/delegated_type.rb @@ -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 @@ -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