e3122d195a2ea3e1ef1a884a156ce85288e36da7
[feedcatcher.git] / vendor / rails / activerecord / lib / active_record / nested_attributes.rb
1 module ActiveRecord
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 = {}
7 end
8
9 # == Nested Attributes
10 #
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
15 # the model.
16 #
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>.
21 #
22 # class Book < ActiveRecord::Base
23 # has_one :author
24 # has_many :pages
25 #
26 # accepts_nested_attributes_for :author, :pages
27 # end
28 #
29 # Note that the <tt>:autosave</tt> option is automatically enabled on every
30 # association that accepts_nested_attributes_for is used for.
31 #
32 # === One-to-one
33 #
34 # Consider a Member model that has one Avatar:
35 #
36 # class Member < ActiveRecord::Base
37 # has_one :avatar
38 # accepts_nested_attributes_for :avatar
39 # end
40 #
41 # Enabling nested attributes on a one-to-one association allows you to
42 # create the member and avatar in one go:
43 #
44 # params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
45 # member = Member.create(params)
46 # member.avatar.id # => 2
47 # member.avatar.icon # => 'smiling'
48 #
49 # It also allows you to update the avatar through the member:
50 #
51 # params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
52 # member.update_attributes params['member']
53 # member.avatar.icon # => 'sad'
54 #
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.
59 #
60 # class Member < ActiveRecord::Base
61 # has_one :avatar
62 # accepts_nested_attributes_for :avatar, :allow_destroy => true
63 # end
64 #
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:
67 #
68 # member.avatar_attributes = { :id => '2', :_delete => '1' }
69 # member.avatar.marked_for_destruction? # => true
70 # member.save
71 # member.avatar #=> nil
72 #
73 # Note that the model will _not_ be destroyed until the parent is saved.
74 #
75 # === One-to-many
76 #
77 # Consider a member that has a number of posts:
78 #
79 # class Member < ActiveRecord::Base
80 # has_many :posts
81 # accepts_nested_attributes_for :posts
82 # end
83 #
84 # You can now set or update attributes on an associated post model through
85 # the attribute hash.
86 #
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+.
90 #
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
96 # ]
97 # }}
98 #
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'
103 #
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:
107 #
108 # class Member < ActiveRecord::Base
109 # has_many :posts
110 # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
111 # end
112 #
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
118 # ]
119 # }}
120 #
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'
125 #
126 # If the hash contains an <tt>id</tt> key that matches an already
127 # associated record, the matching record will be modified:
128 #
129 # member.attributes = {
130 # :name => 'Joe',
131 # :posts_attributes => [
132 # { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
133 # { :id => 2, :title => '[UPDATED] other post' }
134 # ]
135 # }
136 #
137 # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
138 # member.posts.second.title # => '[UPDATED] other post'
139 #
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:
145 #
146 # class Member < ActiveRecord::Base
147 # has_many :posts
148 # accepts_nested_attributes_for :posts, :allow_destroy => true
149 # end
150 #
151 # params = { :member => {
152 # :posts_attributes => [{ :id => '2', :_delete => '1' }]
153 # }}
154 #
155 # member.attributes = params['member']
156 # member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
157 # member.posts.length #=> 2
158 # member.save
159 # member.posts.length # => 1
160 #
161 # === Saving
162 #
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.
167 module ClassMethods
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.
171 #
172 # Supported options:
173 # [:allow_destroy]
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.
177 # [:reject_if]
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.
183 #
184 # Examples:
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)
193
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
198 :one_to_one
199 when :has_many, :has_and_belongs_to_many
200 :collection
201 end
202
203 reflection.options[:autosave] = true
204 self.reject_new_nested_attributes_procs[association_name.to_sym] = options[:reject_if]
205
206 # def pirate_attributes=(attributes)
207 # assign_nested_attributes_for_one_to_one_association(:pirate, attributes, false)
208 # end
209 class_eval %{
210 def #{association_name}_attributes=(attributes)
211 assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, #{options[:allow_destroy]})
212 end
213 }, __FILE__, __LINE__
214 else
215 raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
216 end
217 end
218 end
219 end
220
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.
224 #
225 # See ActionView::Helpers::FormHelper::fields_for for more info.
226 def _delete
227 marked_for_destruction?
228 end
229
230 private
231
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 }
235
236 # Assigns the given attributes to the association.
237 #
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.
241 #
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
247
248 if attributes['id'].blank?
249 unless reject_new_record?(association_name, attributes)
250 send("build_#{association_name}", attributes.except(*UNASSIGNABLE_KEYS))
251 end
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)
254 end
255 end
256
257 # Assigns the given attributes to the collection association.
258 #
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.
264 #
265 # For example:
266 #
267 # assign_nested_attributes_for_collection_association(:people, {
268 # '1' => { :id => '1', :name => 'Peter' },
269 # '2' => { :name => 'John' },
270 # '3' => { :id => '2', :_delete => true }
271 # })
272 #
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
275 # for destruction.
276 #
277 # Also accepts an Array of attribute hashes:
278 #
279 # assign_nested_attributes_for_collection_association(:people, [
280 # { :id => '1', :name => 'Peter' },
281 # { :name => 'John' },
282 # { :id => '2', :_delete => true }
283 # ])
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})"
287 end
288
289 if attributes_collection.is_a? Hash
290 attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
291 end
292
293 attributes_collection.each do |attributes|
294 attributes = attributes.stringify_keys
295
296 if attributes['id'].blank?
297 unless reject_new_record?(association_name, attributes)
298 send(association_name).build(attributes.except(*UNASSIGNABLE_KEYS))
299 end
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)
302 end
303 end
304 end
305
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
311 else
312 record.attributes = attributes.except(*UNASSIGNABLE_KEYS)
313 end
314 end
315
316 # Determines if a hash contains a truthy _delete key.
317 def has_delete_flag?(hash)
318 ConnectionAdapters::Column.value_to_boolean hash['_delete']
319 end
320
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)
327 end
328 end
329 end