2 module NestedAttributes
#:nodoc:
3 def self.included(base
)
4 base
.extend(ClassMethods
)
5 base
.class_inheritable_accessor
:reject_new_nested_attributes_procs, :instance_writer => false
6 base
.reject_new_nested_attributes_procs
= {}
11 # Nested attributes allow you to save attributes on associated records
12 # through the parent. By default nested attribute updating is turned off,
13 # you can enable it using the accepts_nested_attributes_for class method.
14 # When you enable nested attributes an attribute writer is defined on
17 # The attribute writer is named after the association, which means that
18 # in the following example, two new methods are added to your model:
19 # <tt>author_attributes=(attributes)</tt> and
20 # <tt>pages_attributes=(attributes)</tt>.
22 # class Book < ActiveRecord::Base
26 # accepts_nested_attributes_for :author, :pages
29 # Note that the <tt>:autosave</tt> option is automatically enabled on every
30 # association that accepts_nested_attributes_for is used for.
34 # Consider a Member model that has one Avatar:
36 # class Member < ActiveRecord::Base
38 # accepts_nested_attributes_for :avatar
41 # Enabling nested attributes on a one-to-one association allows you to
42 # create the member and avatar in one go:
44 # params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
45 # member = Member.create(params)
46 # member.avatar.id # => 2
47 # member.avatar.icon # => 'smiling'
49 # It also allows you to update the avatar through the member:
51 # params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
52 # member.update_attributes params['member']
53 # member.avatar.icon # => 'sad'
55 # By default you will only be able to set and update attributes on the
56 # associated model. If you want to destroy the associated model through the
57 # attributes hash, you have to enable it first using the
58 # <tt>:allow_destroy</tt> option.
60 # class Member < ActiveRecord::Base
62 # accepts_nested_attributes_for :avatar, :allow_destroy => true
65 # Now, when you add the <tt>_delete</tt> key to the attributes hash, with a
66 # value that evaluates to +true+, you will destroy the associated model:
68 # member.avatar_attributes = { :id => '2', :_delete => '1' }
69 # member.avatar.marked_for_destruction? # => true
71 # member.avatar #=> nil
73 # Note that the model will _not_ be destroyed until the parent is saved.
77 # Consider a member that has a number of posts:
79 # class Member < ActiveRecord::Base
81 # accepts_nested_attributes_for :posts
84 # You can now set or update attributes on an associated post model through
87 # For each hash that does _not_ have an <tt>id</tt> key a new record will
88 # be instantiated, unless the hash also contains a <tt>_delete</tt> key
89 # that evaluates to +true+.
91 # params = { :member => {
92 # :name => 'joe', :posts_attributes => [
93 # { :title => 'Kari, the awesome Ruby documentation browser!' },
94 # { :title => 'The egalitarian assumption of the modern citizen' },
95 # { :title => '', :_delete => '1' } # this will be ignored
99 # member = Member.create(params['member'])
100 # member.posts.length # => 2
101 # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
102 # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
104 # You may also set a :reject_if proc to silently ignore any new record
105 # hashes if they fail to pass your criteria. For example, the previous
106 # example could be rewritten as:
108 # class Member < ActiveRecord::Base
110 # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
113 # params = { :member => {
114 # :name => 'joe', :posts_attributes => [
115 # { :title => 'Kari, the awesome Ruby documentation browser!' },
116 # { :title => 'The egalitarian assumption of the modern citizen' },
117 # { :title => '' } # this will be ignored because of the :reject_if proc
121 # member = Member.create(params['member'])
122 # member.posts.length # => 2
123 # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
124 # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
126 # If the hash contains an <tt>id</tt> key that matches an already
127 # associated record, the matching record will be modified:
129 # member.attributes = {
131 # :posts_attributes => [
132 # { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
133 # { :id => 2, :title => '[UPDATED] other post' }
137 # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
138 # member.posts.second.title # => '[UPDATED] other post'
140 # By default the associated records are protected from being destroyed. If
141 # you want to destroy any of the associated records through the attributes
142 # hash, you have to enable it first using the <tt>:allow_destroy</tt>
143 # option. This will allow you to also use the <tt>_delete</tt> key to
144 # destroy existing records:
146 # class Member < ActiveRecord::Base
148 # accepts_nested_attributes_for :posts, :allow_destroy => true
151 # params = { :member => {
152 # :posts_attributes => [{ :id => '2', :_delete => '1' }]
155 # member.attributes = params['member']
156 # member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
157 # member.posts.length #=> 2
159 # member.posts.length # => 1
163 # All changes to models, including the destruction of those marked for
164 # destruction, are saved and destroyed automatically and atomically when
165 # the parent model is saved. This happens inside the transaction initiated
166 # by the parents save method. See ActiveRecord::AutosaveAssociation.
168 # Defines an attributes writer for the specified association(s). If you
169 # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
170 # will need to add the attribute writer to the allowed list.
174 # If true, destroys any members from the attributes hash with a
175 # <tt>_delete</tt> key and a value that evaluates to +true+
176 # (eg. 1, '1', true, or 'true'). This option is off by default.
178 # Allows you to specify a Proc that checks whether a record should be
179 # built for a certain attribute hash. The hash is passed to the Proc
180 # and the Proc should return either +true+ or +false+. When no Proc
181 # is specified a record will be built for all attribute hashes that
182 # do not have a <tt>_delete</tt> that evaluates to true.
185 # # creates avatar_attributes=
186 # accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
187 # # creates avatar_attributes= and posts_attributes=
188 # accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
189 def accepts_nested_attributes_for(*attr_names
)
190 options
= { :allow_destroy => false }
191 options
.update(attr_names
.extract_options
!)
192 options
.assert_valid_keys(:allow_destroy, :reject_if)
194 attr_names
.each
do |association_name
|
195 if reflection
= reflect_on_association(association_name
)
196 type
= case reflection
.macro
197 when :has_one, :belongs_to
199 when :has_many, :has_and_belongs_to_many
203 reflection
.options
[:autosave] = true
204 self.reject_new_nested_attributes_procs
[association_name
.to_sym
] = options
[:reject_if]
206 # def pirate_attributes=(attributes)
207 # assign_nested_attributes_for_one_to_one_association(:pirate, attributes, false)
210 def #{association_name}_attributes=(attributes)
211 assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, #{options[:allow_destroy]})
213 }, __FILE__, __LINE__
215 raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
221 # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
222 # used in conjunction with fields_for to build a form element for the
223 # destruction of this association.
225 # See ActionView::Helpers::FormHelper::fields_for for more info.
227 marked_for_destruction?
232 # Attribute hash keys that should not be assigned as normal attributes.
233 # These hash keys are nested attributes implementation details.
234 UNASSIGNABLE_KEYS = %w{ id _delete }
236 # Assigns the given attributes to the association.
238 # If the given attributes include an <tt>:id</tt> that matches the existing
239 # record’s id, then the existing record will be modified. Otherwise a new
240 # record will be built.
242 # If the given attributes include a matching <tt>:id</tt> attribute _and_ a
243 # <tt>:_delete</tt> key set to a truthy value, then the existing record
244 # will be marked for destruction.
245 def assign_nested_attributes_for_one_to_one_association(association_name, attributes, allow_destroy)
246 attributes = attributes.stringify_keys
248 if attributes['id'].blank?
249 unless reject_new_record?(association_name, attributes)
250 send("build_#{association_name}", attributes.except(*UNASSIGNABLE_KEYS))
252 elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s
253 assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
257 # Assigns the given attributes to the collection association.
259 # Hashes with an <tt>:id</tt> value matching an existing associated record
260 # will update that record. Hashes without an <tt>:id</tt> value will build
261 # a new record for the association. Hashes with a matching <tt>:id</tt>
262 # value and a <tt>:_delete</tt> key set to a truthy value will mark the
263 # matched record for destruction.
267 # assign_nested_attributes_for_collection_association(:people, {
268 # '1' => { :id => '1', :name => 'Peter' },
269 # '2' => { :name => 'John' },
270 # '3' => { :id => '2', :_delete => true }
273 # Will update the name of the Person with ID 1, build a new associated
274 # person with the name `John', and mark the associatied Person with ID 2
277 # Also accepts an Array of attribute hashes:
279 # assign_nested_attributes_for_collection_association(:people, [
280 # { :id => '1', :name => 'Peter' },
281 # { :name => 'John' },
282 # { :id => '2', :_delete => true }
284 def assign_nested_attributes_for_collection_association(association_name, attributes_collection, allow_destroy)
285 unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
286 raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
289 if attributes_collection.is_a? Hash
290 attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
293 attributes_collection.each do |attributes|
294 attributes = attributes.stringify_keys
296 if attributes['id'].blank?
297 unless reject_new_record?(association_name, attributes)
298 send(association_name).build(attributes.except(*UNASSIGNABLE_KEYS))
300 elsif existing_record = send(association_name).detect { |record| record.id.to_s == attributes['id'].to_s }
301 assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
306 # Updates a record with the +attributes+ or marks it for destruction if
307 # +allow_destroy+ is +true+ and has_delete_flag? returns +true+.
308 def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
309 if has_delete_flag?(attributes) && allow_destroy
310 record.mark_for_destruction
312 record.attributes = attributes.except(*UNASSIGNABLE_KEYS)
316 # Determines if a hash contains a truthy _delete key.
317 def has_delete_flag?(hash)
318 ConnectionAdapters::Column.value_to_boolean hash['_delete']
321 # Determines if a new record should be build by checking for
322 # has_delete_flag? or if a <tt>:reject_if</tt> proc exists for this
323 # association and evaluates to +true+.
324 def reject_new_record?(association_name, attributes)
325 has_delete_flag?(attributes) ||
326 self.class.reject_new_nested_attributes_procs[association_name].try(:call, attributes)