sskirby-activerecord 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. data/CHANGELOG.md +6749 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.rdoc +222 -0
  4. data/examples/associations.png +0 -0
  5. data/examples/performance.rb +177 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record.rb +147 -0
  8. data/lib/active_record/aggregations.rb +255 -0
  9. data/lib/active_record/associations.rb +1604 -0
  10. data/lib/active_record/associations/alias_tracker.rb +79 -0
  11. data/lib/active_record/associations/association.rb +239 -0
  12. data/lib/active_record/associations/association_scope.rb +119 -0
  13. data/lib/active_record/associations/belongs_to_association.rb +79 -0
  14. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +34 -0
  15. data/lib/active_record/associations/builder/association.rb +55 -0
  16. data/lib/active_record/associations/builder/belongs_to.rb +85 -0
  17. data/lib/active_record/associations/builder/collection_association.rb +75 -0
  18. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +57 -0
  19. data/lib/active_record/associations/builder/has_many.rb +71 -0
  20. data/lib/active_record/associations/builder/has_one.rb +62 -0
  21. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  22. data/lib/active_record/associations/collection_association.rb +574 -0
  23. data/lib/active_record/associations/collection_proxy.rb +132 -0
  24. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +62 -0
  25. data/lib/active_record/associations/has_many_association.rb +108 -0
  26. data/lib/active_record/associations/has_many_through_association.rb +180 -0
  27. data/lib/active_record/associations/has_one_association.rb +73 -0
  28. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  29. data/lib/active_record/associations/join_dependency.rb +214 -0
  30. data/lib/active_record/associations/join_dependency/join_association.rb +154 -0
  31. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  32. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  33. data/lib/active_record/associations/join_helper.rb +55 -0
  34. data/lib/active_record/associations/preloader.rb +177 -0
  35. data/lib/active_record/associations/preloader/association.rb +127 -0
  36. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  37. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  38. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  39. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  40. data/lib/active_record/associations/preloader/has_many_through.rb +15 -0
  41. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  42. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  43. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  44. data/lib/active_record/associations/preloader/through_association.rb +67 -0
  45. data/lib/active_record/associations/singular_association.rb +64 -0
  46. data/lib/active_record/associations/through_association.rb +83 -0
  47. data/lib/active_record/attribute_assignment.rb +221 -0
  48. data/lib/active_record/attribute_methods.rb +272 -0
  49. data/lib/active_record/attribute_methods/before_type_cast.rb +31 -0
  50. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
  51. data/lib/active_record/attribute_methods/dirty.rb +101 -0
  52. data/lib/active_record/attribute_methods/primary_key.rb +114 -0
  53. data/lib/active_record/attribute_methods/query.rb +39 -0
  54. data/lib/active_record/attribute_methods/read.rb +135 -0
  55. data/lib/active_record/attribute_methods/serialization.rb +93 -0
  56. data/lib/active_record/attribute_methods/time_zone_conversion.rb +62 -0
  57. data/lib/active_record/attribute_methods/write.rb +69 -0
  58. data/lib/active_record/autosave_association.rb +422 -0
  59. data/lib/active_record/base.rb +716 -0
  60. data/lib/active_record/callbacks.rb +275 -0
  61. data/lib/active_record/coders/yaml_column.rb +41 -0
  62. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +452 -0
  63. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +188 -0
  64. data/lib/active_record/connection_adapters/abstract/database_limits.rb +58 -0
  65. data/lib/active_record/connection_adapters/abstract/database_statements.rb +388 -0
  66. data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -0
  67. data/lib/active_record/connection_adapters/abstract/quoting.rb +115 -0
  68. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +492 -0
  69. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +598 -0
  70. data/lib/active_record/connection_adapters/abstract_adapter.rb +296 -0
  71. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +653 -0
  72. data/lib/active_record/connection_adapters/column.rb +270 -0
  73. data/lib/active_record/connection_adapters/mysql2_adapter.rb +288 -0
  74. data/lib/active_record/connection_adapters/mysql_adapter.rb +426 -0
  75. data/lib/active_record/connection_adapters/postgresql_adapter.rb +1261 -0
  76. data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
  77. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +55 -0
  78. data/lib/active_record/connection_adapters/sqlite_adapter.rb +577 -0
  79. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  80. data/lib/active_record/counter_cache.rb +119 -0
  81. data/lib/active_record/dynamic_finder_match.rb +56 -0
  82. data/lib/active_record/dynamic_matchers.rb +79 -0
  83. data/lib/active_record/dynamic_scope_match.rb +23 -0
  84. data/lib/active_record/errors.rb +195 -0
  85. data/lib/active_record/explain.rb +85 -0
  86. data/lib/active_record/explain_subscriber.rb +21 -0
  87. data/lib/active_record/fixtures.rb +906 -0
  88. data/lib/active_record/fixtures/file.rb +65 -0
  89. data/lib/active_record/identity_map.rb +156 -0
  90. data/lib/active_record/inheritance.rb +167 -0
  91. data/lib/active_record/integration.rb +49 -0
  92. data/lib/active_record/locale/en.yml +40 -0
  93. data/lib/active_record/locking/optimistic.rb +183 -0
  94. data/lib/active_record/locking/pessimistic.rb +77 -0
  95. data/lib/active_record/log_subscriber.rb +68 -0
  96. data/lib/active_record/migration.rb +765 -0
  97. data/lib/active_record/migration/command_recorder.rb +105 -0
  98. data/lib/active_record/model_schema.rb +366 -0
  99. data/lib/active_record/nested_attributes.rb +469 -0
  100. data/lib/active_record/observer.rb +121 -0
  101. data/lib/active_record/persistence.rb +372 -0
  102. data/lib/active_record/query_cache.rb +74 -0
  103. data/lib/active_record/querying.rb +58 -0
  104. data/lib/active_record/railtie.rb +119 -0
  105. data/lib/active_record/railties/console_sandbox.rb +6 -0
  106. data/lib/active_record/railties/controller_runtime.rb +49 -0
  107. data/lib/active_record/railties/databases.rake +620 -0
  108. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  109. data/lib/active_record/readonly_attributes.rb +26 -0
  110. data/lib/active_record/reflection.rb +534 -0
  111. data/lib/active_record/relation.rb +534 -0
  112. data/lib/active_record/relation/batches.rb +90 -0
  113. data/lib/active_record/relation/calculations.rb +354 -0
  114. data/lib/active_record/relation/delegation.rb +49 -0
  115. data/lib/active_record/relation/finder_methods.rb +398 -0
  116. data/lib/active_record/relation/predicate_builder.rb +58 -0
  117. data/lib/active_record/relation/query_methods.rb +417 -0
  118. data/lib/active_record/relation/spawn_methods.rb +148 -0
  119. data/lib/active_record/result.rb +34 -0
  120. data/lib/active_record/sanitization.rb +194 -0
  121. data/lib/active_record/schema.rb +58 -0
  122. data/lib/active_record/schema_dumper.rb +204 -0
  123. data/lib/active_record/scoping.rb +152 -0
  124. data/lib/active_record/scoping/default.rb +142 -0
  125. data/lib/active_record/scoping/named.rb +202 -0
  126. data/lib/active_record/serialization.rb +18 -0
  127. data/lib/active_record/serializers/xml_serializer.rb +202 -0
  128. data/lib/active_record/session_store.rb +358 -0
  129. data/lib/active_record/store.rb +50 -0
  130. data/lib/active_record/test_case.rb +73 -0
  131. data/lib/active_record/timestamp.rb +113 -0
  132. data/lib/active_record/transactions.rb +360 -0
  133. data/lib/active_record/translation.rb +22 -0
  134. data/lib/active_record/validations.rb +83 -0
  135. data/lib/active_record/validations/associated.rb +43 -0
  136. data/lib/active_record/validations/uniqueness.rb +180 -0
  137. data/lib/active_record/version.rb +10 -0
  138. data/lib/rails/generators/active_record.rb +25 -0
  139. data/lib/rails/generators/active_record/migration.rb +15 -0
  140. data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
  141. data/lib/rails/generators/active_record/migration/templates/migration.rb +31 -0
  142. data/lib/rails/generators/active_record/model/model_generator.rb +43 -0
  143. data/lib/rails/generators/active_record/model/templates/migration.rb +15 -0
  144. data/lib/rails/generators/active_record/model/templates/model.rb +7 -0
  145. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  146. data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
  147. data/lib/rails/generators/active_record/observer/templates/observer.rb +4 -0
  148. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +25 -0
  149. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +12 -0
  150. metadata +242 -0
@@ -0,0 +1,469 @@
1
+ require 'active_support/core_ext/hash/except'
2
+ require 'active_support/core_ext/object/try'
3
+ require 'active_support/core_ext/object/blank'
4
+ require 'active_support/core_ext/hash/indifferent_access'
5
+ require 'active_support/core_ext/class/attribute'
6
+
7
+ module ActiveRecord
8
+ module NestedAttributes #:nodoc:
9
+ class TooManyRecords < ActiveRecordError
10
+ end
11
+
12
+ extend ActiveSupport::Concern
13
+
14
+ included do
15
+ class_attribute :nested_attributes_options, :instance_writer => false
16
+ self.nested_attributes_options = {}
17
+ end
18
+
19
+ # = Active Record Nested Attributes
20
+ #
21
+ # Nested attributes allow you to save attributes on associated records
22
+ # through the parent. By default nested attribute updating is turned off,
23
+ # you can enable it using the accepts_nested_attributes_for class method.
24
+ # When you enable nested attributes an attribute writer is defined on
25
+ # the model.
26
+ #
27
+ # The attribute writer is named after the association, which means that
28
+ # in the following example, two new methods are added to your model:
29
+ #
30
+ # <tt>author_attributes=(attributes)</tt> and
31
+ # <tt>pages_attributes=(attributes)</tt>.
32
+ #
33
+ # class Book < ActiveRecord::Base
34
+ # has_one :author
35
+ # has_many :pages
36
+ #
37
+ # accepts_nested_attributes_for :author, :pages
38
+ # end
39
+ #
40
+ # Note that the <tt>:autosave</tt> option is automatically enabled on every
41
+ # association that accepts_nested_attributes_for is used for.
42
+ #
43
+ # === One-to-one
44
+ #
45
+ # Consider a Member model that has one Avatar:
46
+ #
47
+ # class Member < ActiveRecord::Base
48
+ # has_one :avatar
49
+ # accepts_nested_attributes_for :avatar
50
+ # end
51
+ #
52
+ # Enabling nested attributes on a one-to-one association allows you to
53
+ # create the member and avatar in one go:
54
+ #
55
+ # params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
56
+ # member = Member.create(params[:member])
57
+ # member.avatar.id # => 2
58
+ # member.avatar.icon # => 'smiling'
59
+ #
60
+ # It also allows you to update the avatar through the member:
61
+ #
62
+ # params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
63
+ # member.update_attributes params[:member]
64
+ # member.avatar.icon # => 'sad'
65
+ #
66
+ # By default you will only be able to set and update attributes on the
67
+ # associated model. If you want to destroy the associated model through the
68
+ # attributes hash, you have to enable it first using the
69
+ # <tt>:allow_destroy</tt> option.
70
+ #
71
+ # class Member < ActiveRecord::Base
72
+ # has_one :avatar
73
+ # accepts_nested_attributes_for :avatar, :allow_destroy => true
74
+ # end
75
+ #
76
+ # Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
77
+ # value that evaluates to +true+, you will destroy the associated model:
78
+ #
79
+ # member.avatar_attributes = { :id => '2', :_destroy => '1' }
80
+ # member.avatar.marked_for_destruction? # => true
81
+ # member.save
82
+ # member.reload.avatar # => nil
83
+ #
84
+ # Note that the model will _not_ be destroyed until the parent is saved.
85
+ #
86
+ # === One-to-many
87
+ #
88
+ # Consider a member that has a number of posts:
89
+ #
90
+ # class Member < ActiveRecord::Base
91
+ # has_many :posts
92
+ # accepts_nested_attributes_for :posts
93
+ # end
94
+ #
95
+ # You can now set or update attributes on an associated post model through
96
+ # the attribute hash.
97
+ #
98
+ # For each hash that does _not_ have an <tt>id</tt> key a new record will
99
+ # be instantiated, unless the hash also contains a <tt>_destroy</tt> key
100
+ # that evaluates to +true+.
101
+ #
102
+ # params = { :member => {
103
+ # :name => 'joe', :posts_attributes => [
104
+ # { :title => 'Kari, the awesome Ruby documentation browser!' },
105
+ # { :title => 'The egalitarian assumption of the modern citizen' },
106
+ # { :title => '', :_destroy => '1' } # this will be ignored
107
+ # ]
108
+ # }}
109
+ #
110
+ # member = Member.create(params['member'])
111
+ # member.posts.length # => 2
112
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
113
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
114
+ #
115
+ # You may also set a :reject_if proc to silently ignore any new record
116
+ # hashes if they fail to pass your criteria. For example, the previous
117
+ # example could be rewritten as:
118
+ #
119
+ # class Member < ActiveRecord::Base
120
+ # has_many :posts
121
+ # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
122
+ # end
123
+ #
124
+ # params = { :member => {
125
+ # :name => 'joe', :posts_attributes => [
126
+ # { :title => 'Kari, the awesome Ruby documentation browser!' },
127
+ # { :title => 'The egalitarian assumption of the modern citizen' },
128
+ # { :title => '' } # this will be ignored because of the :reject_if proc
129
+ # ]
130
+ # }}
131
+ #
132
+ # member = Member.create(params['member'])
133
+ # member.posts.length # => 2
134
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
135
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
136
+ #
137
+ # Alternatively, :reject_if also accepts a symbol for using methods:
138
+ #
139
+ # class Member < ActiveRecord::Base
140
+ # has_many :posts
141
+ # accepts_nested_attributes_for :posts, :reject_if => :new_record?
142
+ # end
143
+ #
144
+ # class Member < ActiveRecord::Base
145
+ # has_many :posts
146
+ # accepts_nested_attributes_for :posts, :reject_if => :reject_posts
147
+ #
148
+ # def reject_posts(attributed)
149
+ # attributed['title'].blank?
150
+ # end
151
+ # end
152
+ #
153
+ # If the hash contains an <tt>id</tt> key that matches an already
154
+ # associated record, the matching record will be modified:
155
+ #
156
+ # member.attributes = {
157
+ # :name => 'Joe',
158
+ # :posts_attributes => [
159
+ # { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
160
+ # { :id => 2, :title => '[UPDATED] other post' }
161
+ # ]
162
+ # }
163
+ #
164
+ # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
165
+ # member.posts.second.title # => '[UPDATED] other post'
166
+ #
167
+ # By default the associated records are protected from being destroyed. If
168
+ # you want to destroy any of the associated records through the attributes
169
+ # hash, you have to enable it first using the <tt>:allow_destroy</tt>
170
+ # option. This will allow you to also use the <tt>_destroy</tt> key to
171
+ # destroy existing records:
172
+ #
173
+ # class Member < ActiveRecord::Base
174
+ # has_many :posts
175
+ # accepts_nested_attributes_for :posts, :allow_destroy => true
176
+ # end
177
+ #
178
+ # params = { :member => {
179
+ # :posts_attributes => [{ :id => '2', :_destroy => '1' }]
180
+ # }}
181
+ #
182
+ # member.attributes = params['member']
183
+ # member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
184
+ # member.posts.length # => 2
185
+ # member.save
186
+ # member.reload.posts.length # => 1
187
+ #
188
+ # === Saving
189
+ #
190
+ # All changes to models, including the destruction of those marked for
191
+ # destruction, are saved and destroyed automatically and atomically when
192
+ # the parent model is saved. This happens inside the transaction initiated
193
+ # by the parents save method. See ActiveRecord::AutosaveAssociation.
194
+ #
195
+ # === Using with attr_accessible
196
+ #
197
+ # The use of <tt>attr_accessible</tt> can interfere with nested attributes
198
+ # if you're not careful. For example, if the <tt>Member</tt> model above
199
+ # was using <tt>attr_accessible</tt> like this:
200
+ #
201
+ # attr_accessible :name
202
+ #
203
+ # You would need to modify it to look like this:
204
+ #
205
+ # attr_accessible :name, :posts_attributes
206
+ #
207
+ # === Validating the presence of a parent model
208
+ #
209
+ # If you want to validate that a child record is associated with a parent
210
+ # record, you can use <tt>validates_presence_of</tt> and
211
+ # <tt>inverse_of</tt> as this example illustrates:
212
+ #
213
+ # class Member < ActiveRecord::Base
214
+ # has_many :posts, :inverse_of => :member
215
+ # accepts_nested_attributes_for :posts
216
+ # end
217
+ #
218
+ # class Post < ActiveRecord::Base
219
+ # belongs_to :member, :inverse_of => :posts
220
+ # validates_presence_of :member
221
+ # end
222
+ module ClassMethods
223
+ REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
224
+
225
+ # Defines an attributes writer for the specified association(s). If you
226
+ # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
227
+ # will need to add the attribute writer to the allowed list.
228
+ #
229
+ # Supported options:
230
+ # [:allow_destroy]
231
+ # If true, destroys any members from the attributes hash with a
232
+ # <tt>_destroy</tt> key and a value that evaluates to +true+
233
+ # (eg. 1, '1', true, or 'true'). This option is off by default.
234
+ # [:reject_if]
235
+ # Allows you to specify a Proc or a Symbol pointing to a method
236
+ # that checks whether a record should be built for a certain attribute
237
+ # hash. The hash is passed to the supplied Proc or the method
238
+ # and it should return either +true+ or +false+. When no :reject_if
239
+ # is specified, a record will be built for all attribute hashes that
240
+ # do not have a <tt>_destroy</tt> value that evaluates to true.
241
+ # Passing <tt>:all_blank</tt> instead of a Proc will create a proc
242
+ # that will reject a record where all the attributes are blank excluding
243
+ # any value for _destroy.
244
+ # [:limit]
245
+ # Allows you to specify the maximum number of the associated records that
246
+ # can be processed with the nested attributes. If the size of the
247
+ # nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
248
+ # exception is raised. If omitted, any number associations can be processed.
249
+ # Note that the :limit option is only applicable to one-to-many associations.
250
+ # [:update_only]
251
+ # Allows you to specify that an existing record may only be updated.
252
+ # A new record may only be created when there is no existing record.
253
+ # This option only works for one-to-one associations and is ignored for
254
+ # collection associations. This option is off by default.
255
+ #
256
+ # Examples:
257
+ # # creates avatar_attributes=
258
+ # accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
259
+ # # creates avatar_attributes=
260
+ # accepts_nested_attributes_for :avatar, :reject_if => :all_blank
261
+ # # creates avatar_attributes= and posts_attributes=
262
+ # accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
263
+ def accepts_nested_attributes_for(*attr_names)
264
+ options = { :allow_destroy => false, :update_only => false }
265
+ options.update(attr_names.extract_options!)
266
+ options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
267
+ options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
268
+
269
+ attr_names.each do |association_name|
270
+ if reflection = reflect_on_association(association_name)
271
+ reflection.options[:autosave] = true
272
+ add_autosave_association_callbacks(reflection)
273
+
274
+ nested_attributes_options = self.nested_attributes_options.dup
275
+ nested_attributes_options[association_name.to_sym] = options
276
+ self.nested_attributes_options = nested_attributes_options
277
+
278
+ type = (reflection.collection? ? :collection : :one_to_one)
279
+
280
+ # def pirate_attributes=(attributes)
281
+ # assign_nested_attributes_for_one_to_one_association(:pirate, attributes, mass_assignment_options)
282
+ # end
283
+ class_eval <<-eoruby, __FILE__, __LINE__ + 1
284
+ if method_defined?(:#{association_name}_attributes=)
285
+ remove_method(:#{association_name}_attributes=)
286
+ end
287
+ def #{association_name}_attributes=(attributes)
288
+ assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, mass_assignment_options)
289
+ end
290
+ eoruby
291
+ else
292
+ raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
293
+ end
294
+ end
295
+ end
296
+ end
297
+
298
+ # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
299
+ # used in conjunction with fields_for to build a form element for the
300
+ # destruction of this association.
301
+ #
302
+ # See ActionView::Helpers::FormHelper::fields_for for more info.
303
+ def _destroy
304
+ marked_for_destruction?
305
+ end
306
+
307
+ private
308
+
309
+ # Attribute hash keys that should not be assigned as normal attributes.
310
+ # These hash keys are nested attributes implementation details.
311
+ UNASSIGNABLE_KEYS = %w( id _destroy )
312
+
313
+ # Assigns the given attributes to the association.
314
+ #
315
+ # If update_only is false and the given attributes include an <tt>:id</tt>
316
+ # that matches the existing record's id, then the existing record will be
317
+ # modified. If update_only is true, a new record is only created when no
318
+ # object exists. Otherwise a new record will be built.
319
+ #
320
+ # If the given attributes include a matching <tt>:id</tt> attribute, or
321
+ # update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
322
+ # then the existing record will be marked for destruction.
323
+ def assign_nested_attributes_for_one_to_one_association(association_name, attributes, assignment_opts = {})
324
+ options = self.nested_attributes_options[association_name]
325
+ attributes = attributes.with_indifferent_access
326
+
327
+ if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
328
+ (options[:update_only] || record.id.to_s == attributes['id'].to_s)
329
+ assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy], assignment_opts) unless call_reject_if(association_name, attributes)
330
+
331
+ elsif attributes['id'].present? && !assignment_opts[:without_protection]
332
+ raise_nested_attributes_record_not_found(association_name, attributes['id'])
333
+
334
+ elsif !reject_new_record?(association_name, attributes)
335
+ method = "build_#{association_name}"
336
+ if respond_to?(method)
337
+ send(method, attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
338
+ else
339
+ raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
340
+ end
341
+ end
342
+ end
343
+
344
+ # Assigns the given attributes to the collection association.
345
+ #
346
+ # Hashes with an <tt>:id</tt> value matching an existing associated record
347
+ # will update that record. Hashes without an <tt>:id</tt> value will build
348
+ # a new record for the association. Hashes with a matching <tt>:id</tt>
349
+ # value and a <tt>:_destroy</tt> key set to a truthy value will mark the
350
+ # matched record for destruction.
351
+ #
352
+ # For example:
353
+ #
354
+ # assign_nested_attributes_for_collection_association(:people, {
355
+ # '1' => { :id => '1', :name => 'Peter' },
356
+ # '2' => { :name => 'John' },
357
+ # '3' => { :id => '2', :_destroy => true }
358
+ # })
359
+ #
360
+ # Will update the name of the Person with ID 1, build a new associated
361
+ # person with the name `John', and mark the associated Person with ID 2
362
+ # for destruction.
363
+ #
364
+ # Also accepts an Array of attribute hashes:
365
+ #
366
+ # assign_nested_attributes_for_collection_association(:people, [
367
+ # { :id => '1', :name => 'Peter' },
368
+ # { :name => 'John' },
369
+ # { :id => '2', :_destroy => true }
370
+ # ])
371
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection, assignment_opts = {})
372
+ options = self.nested_attributes_options[association_name]
373
+
374
+ unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
375
+ raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
376
+ end
377
+
378
+ if options[:limit] && attributes_collection.size > options[:limit]
379
+ raise TooManyRecords, "Maximum #{options[:limit]} records are allowed. Got #{attributes_collection.size} records instead."
380
+ end
381
+
382
+ if attributes_collection.is_a? Hash
383
+ keys = attributes_collection.keys
384
+ attributes_collection = if keys.include?('id') || keys.include?(:id)
385
+ Array.wrap(attributes_collection)
386
+ else
387
+ attributes_collection.values
388
+ end
389
+ end
390
+
391
+ association = association(association_name)
392
+
393
+ existing_records = if association.loaded?
394
+ association.target
395
+ else
396
+ attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
397
+ attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
398
+ end
399
+
400
+ attributes_collection.each do |attributes|
401
+ attributes = attributes.with_indifferent_access
402
+
403
+ if attributes['id'].blank?
404
+ unless reject_new_record?(association_name, attributes)
405
+ association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
406
+ end
407
+ elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
408
+ unless association.loaded? || call_reject_if(association_name, attributes)
409
+ # Make sure we are operating on the actual object which is in the association's
410
+ # proxy_target array (either by finding it, or adding it if not found)
411
+ target_record = association.target.detect { |record| record == existing_record }
412
+
413
+ if target_record
414
+ existing_record = target_record
415
+ else
416
+ association.add_to_target(existing_record)
417
+ end
418
+
419
+ end
420
+
421
+ if !call_reject_if(association_name, attributes)
422
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy], assignment_opts)
423
+ end
424
+ elsif assignment_opts[:without_protection]
425
+ association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
426
+ else
427
+ raise_nested_attributes_record_not_found(association_name, attributes['id'])
428
+ end
429
+ end
430
+ end
431
+
432
+ # Updates a record with the +attributes+ or marks it for destruction if
433
+ # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
434
+ def assign_to_or_mark_for_destruction(record, attributes, allow_destroy, assignment_opts)
435
+ record.assign_attributes(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
436
+ record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
437
+ end
438
+
439
+ # Determines if a hash contains a truthy _destroy key.
440
+ def has_destroy_flag?(hash)
441
+ ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
442
+ end
443
+
444
+ # Determines if a new record should be build by checking for
445
+ # has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
446
+ # association and evaluates to +true+.
447
+ def reject_new_record?(association_name, attributes)
448
+ has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
449
+ end
450
+
451
+ def call_reject_if(association_name, attributes)
452
+ return false if has_destroy_flag?(attributes)
453
+ case callback = self.nested_attributes_options[association_name][:reject_if]
454
+ when Symbol
455
+ method(callback).arity == 0 ? send(callback) : send(callback, attributes)
456
+ when Proc
457
+ callback.call(attributes)
458
+ end
459
+ end
460
+
461
+ def raise_nested_attributes_record_not_found(association_name, record_id)
462
+ raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
463
+ end
464
+
465
+ def unassignable_keys(assignment_opts)
466
+ assignment_opts[:without_protection] ? UNASSIGNABLE_KEYS - %w[id] : UNASSIGNABLE_KEYS
467
+ end
468
+ end
469
+ end