activerecord 4.2.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (221) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +1372 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +218 -0
  5. data/examples/performance.rb +184 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record.rb +173 -0
  8. data/lib/active_record/aggregations.rb +266 -0
  9. data/lib/active_record/association_relation.rb +22 -0
  10. data/lib/active_record/associations.rb +1724 -0
  11. data/lib/active_record/associations/alias_tracker.rb +87 -0
  12. data/lib/active_record/associations/association.rb +253 -0
  13. data/lib/active_record/associations/association_scope.rb +194 -0
  14. data/lib/active_record/associations/belongs_to_association.rb +111 -0
  15. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +40 -0
  16. data/lib/active_record/associations/builder/association.rb +149 -0
  17. data/lib/active_record/associations/builder/belongs_to.rb +116 -0
  18. data/lib/active_record/associations/builder/collection_association.rb +91 -0
  19. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +124 -0
  20. data/lib/active_record/associations/builder/has_many.rb +15 -0
  21. data/lib/active_record/associations/builder/has_one.rb +23 -0
  22. data/lib/active_record/associations/builder/singular_association.rb +38 -0
  23. data/lib/active_record/associations/collection_association.rb +634 -0
  24. data/lib/active_record/associations/collection_proxy.rb +1027 -0
  25. data/lib/active_record/associations/has_many_association.rb +184 -0
  26. data/lib/active_record/associations/has_many_through_association.rb +238 -0
  27. data/lib/active_record/associations/has_one_association.rb +105 -0
  28. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  29. data/lib/active_record/associations/join_dependency.rb +282 -0
  30. data/lib/active_record/associations/join_dependency/join_association.rb +122 -0
  31. data/lib/active_record/associations/join_dependency/join_base.rb +22 -0
  32. data/lib/active_record/associations/join_dependency/join_part.rb +71 -0
  33. data/lib/active_record/associations/preloader.rb +203 -0
  34. data/lib/active_record/associations/preloader/association.rb +162 -0
  35. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  36. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  37. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  38. data/lib/active_record/associations/preloader/has_many_through.rb +19 -0
  39. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  40. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  41. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  42. data/lib/active_record/associations/preloader/through_association.rb +96 -0
  43. data/lib/active_record/associations/singular_association.rb +86 -0
  44. data/lib/active_record/associations/through_association.rb +96 -0
  45. data/lib/active_record/attribute.rb +149 -0
  46. data/lib/active_record/attribute_assignment.rb +212 -0
  47. data/lib/active_record/attribute_decorators.rb +66 -0
  48. data/lib/active_record/attribute_methods.rb +439 -0
  49. data/lib/active_record/attribute_methods/before_type_cast.rb +71 -0
  50. data/lib/active_record/attribute_methods/dirty.rb +181 -0
  51. data/lib/active_record/attribute_methods/primary_key.rb +128 -0
  52. data/lib/active_record/attribute_methods/query.rb +40 -0
  53. data/lib/active_record/attribute_methods/read.rb +103 -0
  54. data/lib/active_record/attribute_methods/serialization.rb +70 -0
  55. data/lib/active_record/attribute_methods/time_zone_conversion.rb +65 -0
  56. data/lib/active_record/attribute_methods/write.rb +83 -0
  57. data/lib/active_record/attribute_set.rb +77 -0
  58. data/lib/active_record/attribute_set/builder.rb +86 -0
  59. data/lib/active_record/attributes.rb +139 -0
  60. data/lib/active_record/autosave_association.rb +439 -0
  61. data/lib/active_record/base.rb +317 -0
  62. data/lib/active_record/callbacks.rb +313 -0
  63. data/lib/active_record/coders/json.rb +13 -0
  64. data/lib/active_record/coders/yaml_column.rb +38 -0
  65. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +659 -0
  66. data/lib/active_record/connection_adapters/abstract/database_limits.rb +67 -0
  67. data/lib/active_record/connection_adapters/abstract/database_statements.rb +373 -0
  68. data/lib/active_record/connection_adapters/abstract/query_cache.rb +95 -0
  69. data/lib/active_record/connection_adapters/abstract/quoting.rb +133 -0
  70. data/lib/active_record/connection_adapters/abstract/savepoints.rb +21 -0
  71. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +125 -0
  72. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +574 -0
  73. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +50 -0
  74. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +991 -0
  75. data/lib/active_record/connection_adapters/abstract/transaction.rb +219 -0
  76. data/lib/active_record/connection_adapters/abstract_adapter.rb +487 -0
  77. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +883 -0
  78. data/lib/active_record/connection_adapters/column.rb +82 -0
  79. data/lib/active_record/connection_adapters/connection_specification.rb +275 -0
  80. data/lib/active_record/connection_adapters/mysql2_adapter.rb +282 -0
  81. data/lib/active_record/connection_adapters/mysql_adapter.rb +491 -0
  82. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +93 -0
  83. data/lib/active_record/connection_adapters/postgresql/column.rb +20 -0
  84. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +232 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid.rb +36 -0
  86. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +99 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +52 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +13 -0
  89. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +14 -0
  90. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +46 -0
  91. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +11 -0
  92. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +27 -0
  93. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +13 -0
  94. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +17 -0
  95. data/lib/active_record/connection_adapters/postgresql/oid/float.rb +21 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +59 -0
  97. data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +13 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/infinity.rb +13 -0
  99. data/lib/active_record/connection_adapters/postgresql/oid/integer.rb +11 -0
  100. data/lib/active_record/connection_adapters/postgresql/oid/json.rb +35 -0
  101. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +23 -0
  102. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +43 -0
  103. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +43 -0
  104. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +79 -0
  105. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +15 -0
  106. data/lib/active_record/connection_adapters/postgresql/oid/time.rb +11 -0
  107. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +97 -0
  108. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +21 -0
  109. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +26 -0
  110. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +28 -0
  111. data/lib/active_record/connection_adapters/postgresql/quoting.rb +108 -0
  112. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  113. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +152 -0
  114. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +588 -0
  115. data/lib/active_record/connection_adapters/postgresql/utils.rb +77 -0
  116. data/lib/active_record/connection_adapters/postgresql_adapter.rb +754 -0
  117. data/lib/active_record/connection_adapters/schema_cache.rb +94 -0
  118. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +628 -0
  119. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  120. data/lib/active_record/connection_handling.rb +132 -0
  121. data/lib/active_record/core.rb +566 -0
  122. data/lib/active_record/counter_cache.rb +175 -0
  123. data/lib/active_record/dynamic_matchers.rb +140 -0
  124. data/lib/active_record/enum.rb +198 -0
  125. data/lib/active_record/errors.rb +252 -0
  126. data/lib/active_record/explain.rb +38 -0
  127. data/lib/active_record/explain_registry.rb +30 -0
  128. data/lib/active_record/explain_subscriber.rb +29 -0
  129. data/lib/active_record/fixture_set/file.rb +56 -0
  130. data/lib/active_record/fixtures.rb +1007 -0
  131. data/lib/active_record/gem_version.rb +15 -0
  132. data/lib/active_record/inheritance.rb +247 -0
  133. data/lib/active_record/integration.rb +113 -0
  134. data/lib/active_record/locale/en.yml +47 -0
  135. data/lib/active_record/locking/optimistic.rb +204 -0
  136. data/lib/active_record/locking/pessimistic.rb +77 -0
  137. data/lib/active_record/log_subscriber.rb +75 -0
  138. data/lib/active_record/migration.rb +1051 -0
  139. data/lib/active_record/migration/command_recorder.rb +197 -0
  140. data/lib/active_record/migration/join_table.rb +15 -0
  141. data/lib/active_record/model_schema.rb +340 -0
  142. data/lib/active_record/nested_attributes.rb +548 -0
  143. data/lib/active_record/no_touching.rb +52 -0
  144. data/lib/active_record/null_relation.rb +81 -0
  145. data/lib/active_record/persistence.rb +532 -0
  146. data/lib/active_record/query_cache.rb +56 -0
  147. data/lib/active_record/querying.rb +68 -0
  148. data/lib/active_record/railtie.rb +162 -0
  149. data/lib/active_record/railties/console_sandbox.rb +5 -0
  150. data/lib/active_record/railties/controller_runtime.rb +50 -0
  151. data/lib/active_record/railties/databases.rake +391 -0
  152. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  153. data/lib/active_record/readonly_attributes.rb +23 -0
  154. data/lib/active_record/reflection.rb +881 -0
  155. data/lib/active_record/relation.rb +681 -0
  156. data/lib/active_record/relation/batches.rb +138 -0
  157. data/lib/active_record/relation/calculations.rb +403 -0
  158. data/lib/active_record/relation/delegation.rb +140 -0
  159. data/lib/active_record/relation/finder_methods.rb +528 -0
  160. data/lib/active_record/relation/merger.rb +170 -0
  161. data/lib/active_record/relation/predicate_builder.rb +126 -0
  162. data/lib/active_record/relation/predicate_builder/array_handler.rb +47 -0
  163. data/lib/active_record/relation/predicate_builder/relation_handler.rb +13 -0
  164. data/lib/active_record/relation/query_methods.rb +1176 -0
  165. data/lib/active_record/relation/spawn_methods.rb +75 -0
  166. data/lib/active_record/result.rb +131 -0
  167. data/lib/active_record/runtime_registry.rb +22 -0
  168. data/lib/active_record/sanitization.rb +191 -0
  169. data/lib/active_record/schema.rb +64 -0
  170. data/lib/active_record/schema_dumper.rb +251 -0
  171. data/lib/active_record/schema_migration.rb +56 -0
  172. data/lib/active_record/scoping.rb +87 -0
  173. data/lib/active_record/scoping/default.rb +134 -0
  174. data/lib/active_record/scoping/named.rb +164 -0
  175. data/lib/active_record/serialization.rb +22 -0
  176. data/lib/active_record/serializers/xml_serializer.rb +193 -0
  177. data/lib/active_record/statement_cache.rb +111 -0
  178. data/lib/active_record/store.rb +205 -0
  179. data/lib/active_record/tasks/database_tasks.rb +296 -0
  180. data/lib/active_record/tasks/mysql_database_tasks.rb +145 -0
  181. data/lib/active_record/tasks/postgresql_database_tasks.rb +90 -0
  182. data/lib/active_record/tasks/sqlite_database_tasks.rb +55 -0
  183. data/lib/active_record/timestamp.rb +121 -0
  184. data/lib/active_record/transactions.rb +417 -0
  185. data/lib/active_record/translation.rb +22 -0
  186. data/lib/active_record/type.rb +23 -0
  187. data/lib/active_record/type/big_integer.rb +13 -0
  188. data/lib/active_record/type/binary.rb +50 -0
  189. data/lib/active_record/type/boolean.rb +30 -0
  190. data/lib/active_record/type/date.rb +46 -0
  191. data/lib/active_record/type/date_time.rb +43 -0
  192. data/lib/active_record/type/decimal.rb +40 -0
  193. data/lib/active_record/type/decimal_without_scale.rb +11 -0
  194. data/lib/active_record/type/decorator.rb +14 -0
  195. data/lib/active_record/type/float.rb +19 -0
  196. data/lib/active_record/type/hash_lookup_type_map.rb +17 -0
  197. data/lib/active_record/type/integer.rb +55 -0
  198. data/lib/active_record/type/mutable.rb +16 -0
  199. data/lib/active_record/type/numeric.rb +36 -0
  200. data/lib/active_record/type/serialized.rb +56 -0
  201. data/lib/active_record/type/string.rb +36 -0
  202. data/lib/active_record/type/text.rb +11 -0
  203. data/lib/active_record/type/time.rb +26 -0
  204. data/lib/active_record/type/time_value.rb +38 -0
  205. data/lib/active_record/type/type_map.rb +64 -0
  206. data/lib/active_record/type/unsigned_integer.rb +15 -0
  207. data/lib/active_record/type/value.rb +101 -0
  208. data/lib/active_record/validations.rb +90 -0
  209. data/lib/active_record/validations/associated.rb +51 -0
  210. data/lib/active_record/validations/presence.rb +67 -0
  211. data/lib/active_record/validations/uniqueness.rb +229 -0
  212. data/lib/active_record/version.rb +8 -0
  213. data/lib/rails/generators/active_record.rb +17 -0
  214. data/lib/rails/generators/active_record/migration.rb +18 -0
  215. data/lib/rails/generators/active_record/migration/migration_generator.rb +70 -0
  216. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +22 -0
  217. data/lib/rails/generators/active_record/migration/templates/migration.rb +45 -0
  218. data/lib/rails/generators/active_record/model/model_generator.rb +52 -0
  219. data/lib/rails/generators/active_record/model/templates/model.rb +10 -0
  220. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  221. metadata +309 -0
@@ -0,0 +1,548 @@
1
+ require 'active_support/core_ext/hash/except'
2
+ require 'active_support/core_ext/object/try'
3
+ require 'active_support/core_ext/hash/indifferent_access'
4
+
5
+ module ActiveRecord
6
+ module NestedAttributes #:nodoc:
7
+ class TooManyRecords < ActiveRecordError
8
+ end
9
+
10
+ extend ActiveSupport::Concern
11
+
12
+ included do
13
+ class_attribute :nested_attributes_options, instance_writer: false
14
+ self.nested_attributes_options = {}
15
+ end
16
+
17
+ # = Active Record Nested Attributes
18
+ #
19
+ # Nested attributes allow you to save attributes on associated records
20
+ # through the parent. By default nested attribute updating is turned off
21
+ # and you can enable it using the accepts_nested_attributes_for class
22
+ # method. When you enable nested attributes an attribute writer is
23
+ # defined on the model.
24
+ #
25
+ # The attribute writer is named after the association, which means that
26
+ # in the following example, two new methods are added to your model:
27
+ #
28
+ # <tt>author_attributes=(attributes)</tt> and
29
+ # <tt>pages_attributes=(attributes)</tt>.
30
+ #
31
+ # class Book < ActiveRecord::Base
32
+ # has_one :author
33
+ # has_many :pages
34
+ #
35
+ # accepts_nested_attributes_for :author, :pages
36
+ # end
37
+ #
38
+ # Note that the <tt>:autosave</tt> option is automatically enabled on every
39
+ # association that accepts_nested_attributes_for is used for.
40
+ #
41
+ # === One-to-one
42
+ #
43
+ # Consider a Member model that has one Avatar:
44
+ #
45
+ # class Member < ActiveRecord::Base
46
+ # has_one :avatar
47
+ # accepts_nested_attributes_for :avatar
48
+ # end
49
+ #
50
+ # Enabling nested attributes on a one-to-one association allows you to
51
+ # create the member and avatar in one go:
52
+ #
53
+ # params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
54
+ # member = Member.create(params[:member])
55
+ # member.avatar.id # => 2
56
+ # member.avatar.icon # => 'smiling'
57
+ #
58
+ # It also allows you to update the avatar through the member:
59
+ #
60
+ # params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
61
+ # member.update params[:member]
62
+ # member.avatar.icon # => 'sad'
63
+ #
64
+ # By default you will only be able to set and update attributes on the
65
+ # associated model. If you want to destroy the associated model through the
66
+ # attributes hash, you have to enable it first using the
67
+ # <tt>:allow_destroy</tt> option.
68
+ #
69
+ # class Member < ActiveRecord::Base
70
+ # has_one :avatar
71
+ # accepts_nested_attributes_for :avatar, allow_destroy: true
72
+ # end
73
+ #
74
+ # Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
75
+ # value that evaluates to +true+, you will destroy the associated model:
76
+ #
77
+ # member.avatar_attributes = { id: '2', _destroy: '1' }
78
+ # member.avatar.marked_for_destruction? # => true
79
+ # member.save
80
+ # member.reload.avatar # => nil
81
+ #
82
+ # Note that the model will _not_ be destroyed until the parent is saved.
83
+ #
84
+ # === One-to-many
85
+ #
86
+ # Consider a member that has a number of posts:
87
+ #
88
+ # class Member < ActiveRecord::Base
89
+ # has_many :posts
90
+ # accepts_nested_attributes_for :posts
91
+ # end
92
+ #
93
+ # You can now set or update attributes on the associated posts through
94
+ # an attribute hash for a member: include the key +:posts_attributes+
95
+ # with an array of hashes of post attributes as a value.
96
+ #
97
+ # For each hash that does _not_ have an <tt>id</tt> key a new record will
98
+ # be instantiated, unless the hash also contains a <tt>_destroy</tt> key
99
+ # that evaluates to +true+.
100
+ #
101
+ # params = { member: {
102
+ # name: 'joe', posts_attributes: [
103
+ # { title: 'Kari, the awesome Ruby documentation browser!' },
104
+ # { title: 'The egalitarian assumption of the modern citizen' },
105
+ # { title: '', _destroy: '1' } # this will be ignored
106
+ # ]
107
+ # }}
108
+ #
109
+ # member = Member.create(params[:member])
110
+ # member.posts.length # => 2
111
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
112
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
113
+ #
114
+ # You may also set a :reject_if proc to silently ignore any new record
115
+ # hashes if they fail to pass your criteria. For example, the previous
116
+ # example could be rewritten as:
117
+ #
118
+ # class Member < ActiveRecord::Base
119
+ # has_many :posts
120
+ # accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }
121
+ # end
122
+ #
123
+ # params = { member: {
124
+ # name: 'joe', posts_attributes: [
125
+ # { title: 'Kari, the awesome Ruby documentation browser!' },
126
+ # { title: 'The egalitarian assumption of the modern citizen' },
127
+ # { title: '' } # this will be ignored because of the :reject_if proc
128
+ # ]
129
+ # }}
130
+ #
131
+ # member = Member.create(params[:member])
132
+ # member.posts.length # => 2
133
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
134
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
135
+ #
136
+ # Alternatively, :reject_if also accepts a symbol for using methods:
137
+ #
138
+ # class Member < ActiveRecord::Base
139
+ # has_many :posts
140
+ # accepts_nested_attributes_for :posts, reject_if: :new_record?
141
+ # end
142
+ #
143
+ # class Member < ActiveRecord::Base
144
+ # has_many :posts
145
+ # accepts_nested_attributes_for :posts, reject_if: :reject_posts
146
+ #
147
+ # def reject_posts(attributed)
148
+ # attributed['title'].blank?
149
+ # end
150
+ # end
151
+ #
152
+ # If the hash contains an <tt>id</tt> key that matches an already
153
+ # associated record, the matching record will be modified:
154
+ #
155
+ # member.attributes = {
156
+ # name: 'Joe',
157
+ # posts_attributes: [
158
+ # { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
159
+ # { id: 2, title: '[UPDATED] other post' }
160
+ # ]
161
+ # }
162
+ #
163
+ # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
164
+ # member.posts.second.title # => '[UPDATED] other post'
165
+ #
166
+ # By default the associated records are protected from being destroyed. If
167
+ # you want to destroy any of the associated records through the attributes
168
+ # hash, you have to enable it first using the <tt>:allow_destroy</tt>
169
+ # option. This will allow you to also use the <tt>_destroy</tt> key to
170
+ # destroy existing records:
171
+ #
172
+ # class Member < ActiveRecord::Base
173
+ # has_many :posts
174
+ # accepts_nested_attributes_for :posts, allow_destroy: true
175
+ # end
176
+ #
177
+ # params = { member: {
178
+ # posts_attributes: [{ id: '2', _destroy: '1' }]
179
+ # }}
180
+ #
181
+ # member.attributes = params[:member]
182
+ # member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
183
+ # member.posts.length # => 2
184
+ # member.save
185
+ # member.reload.posts.length # => 1
186
+ #
187
+ # Nested attributes for an associated collection can also be passed in
188
+ # the form of a hash of hashes instead of an array of hashes:
189
+ #
190
+ # Member.create(name: 'joe',
191
+ # posts_attributes: { first: { title: 'Foo' },
192
+ # second: { title: 'Bar' } })
193
+ #
194
+ # has the same effect as
195
+ #
196
+ # Member.create(name: 'joe',
197
+ # posts_attributes: [ { title: 'Foo' },
198
+ # { title: 'Bar' } ])
199
+ #
200
+ # The keys of the hash which is the value for +:posts_attributes+ are
201
+ # ignored in this case.
202
+ # However, it is not allowed to use +'id'+ or +:id+ for one of
203
+ # such keys, otherwise the hash will be wrapped in an array and
204
+ # interpreted as an attribute hash for a single post.
205
+ #
206
+ # Passing attributes for an associated collection in the form of a hash
207
+ # of hashes can be used with hashes generated from HTTP/HTML parameters,
208
+ # where there maybe no natural way to submit an array of hashes.
209
+ #
210
+ # === Saving
211
+ #
212
+ # All changes to models, including the destruction of those marked for
213
+ # destruction, are saved and destroyed automatically and atomically when
214
+ # the parent model is saved. This happens inside the transaction initiated
215
+ # by the parents save method. See ActiveRecord::AutosaveAssociation.
216
+ #
217
+ # === Validating the presence of a parent model
218
+ #
219
+ # If you want to validate that a child record is associated with a parent
220
+ # record, you can use <tt>validates_presence_of</tt> and
221
+ # <tt>inverse_of</tt> as this example illustrates:
222
+ #
223
+ # class Member < ActiveRecord::Base
224
+ # has_many :posts, inverse_of: :member
225
+ # accepts_nested_attributes_for :posts
226
+ # end
227
+ #
228
+ # class Post < ActiveRecord::Base
229
+ # belongs_to :member, inverse_of: :posts
230
+ # validates_presence_of :member
231
+ # end
232
+ #
233
+ # Note that if you do not specify the <tt>inverse_of</tt> option, then
234
+ # Active Record will try to automatically guess the inverse association
235
+ # based on heuristics.
236
+ #
237
+ # For one-to-one nested associations, if you build the new (in-memory)
238
+ # child object yourself before assignment, then this module will not
239
+ # overwrite it, e.g.:
240
+ #
241
+ # class Member < ActiveRecord::Base
242
+ # has_one :avatar
243
+ # accepts_nested_attributes_for :avatar
244
+ #
245
+ # def avatar
246
+ # super || build_avatar(width: 200)
247
+ # end
248
+ # end
249
+ #
250
+ # member = Member.new
251
+ # member.avatar_attributes = {icon: 'sad'}
252
+ # member.avatar.width # => 200
253
+ module ClassMethods
254
+ REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
255
+
256
+ # Defines an attributes writer for the specified association(s).
257
+ #
258
+ # Supported options:
259
+ # [:allow_destroy]
260
+ # If true, destroys any members from the attributes hash with a
261
+ # <tt>_destroy</tt> key and a value that evaluates to +true+
262
+ # (eg. 1, '1', true, or 'true'). This option is off by default.
263
+ # [:reject_if]
264
+ # Allows you to specify a Proc or a Symbol pointing to a method
265
+ # that checks whether a record should be built for a certain attribute
266
+ # hash. The hash is passed to the supplied Proc or the method
267
+ # and it should return either +true+ or +false+. When no :reject_if
268
+ # is specified, a record will be built for all attribute hashes that
269
+ # do not have a <tt>_destroy</tt> value that evaluates to true.
270
+ # Passing <tt>:all_blank</tt> instead of a Proc will create a proc
271
+ # that will reject a record where all the attributes are blank excluding
272
+ # any value for _destroy.
273
+ # [:limit]
274
+ # Allows you to specify the maximum number of the associated records that
275
+ # can be processed with the nested attributes. Limit also can be specified as a
276
+ # Proc or a Symbol pointing to a method that should return number. If the size of the
277
+ # nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
278
+ # exception is raised. If omitted, any number associations can be processed.
279
+ # Note that the :limit option is only applicable to one-to-many associations.
280
+ # [:update_only]
281
+ # For a one-to-one association, this option allows you to specify how
282
+ # nested attributes are to be used when an associated record already
283
+ # exists. In general, an existing record may either be updated with the
284
+ # new set of attribute values or be replaced by a wholly new record
285
+ # containing those values. By default the :update_only option is +false+
286
+ # and the nested attributes are used to update the existing record only
287
+ # if they include the record's <tt>:id</tt> value. Otherwise a new
288
+ # record will be instantiated and used to replace the existing one.
289
+ # However if the :update_only option is +true+, the nested attributes
290
+ # are used to update the record's attributes always, regardless of
291
+ # whether the <tt>:id</tt> is present. The option is ignored for collection
292
+ # associations.
293
+ #
294
+ # Examples:
295
+ # # creates avatar_attributes=
296
+ # accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
297
+ # # creates avatar_attributes=
298
+ # accepts_nested_attributes_for :avatar, reject_if: :all_blank
299
+ # # creates avatar_attributes= and posts_attributes=
300
+ # accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
301
+ def accepts_nested_attributes_for(*attr_names)
302
+ options = { :allow_destroy => false, :update_only => false }
303
+ options.update(attr_names.extract_options!)
304
+ options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
305
+ options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
306
+
307
+ attr_names.each do |association_name|
308
+ if reflection = _reflect_on_association(association_name)
309
+ reflection.autosave = true
310
+ add_autosave_association_callbacks(reflection)
311
+
312
+ nested_attributes_options = self.nested_attributes_options.dup
313
+ nested_attributes_options[association_name.to_sym] = options
314
+ self.nested_attributes_options = nested_attributes_options
315
+
316
+ type = (reflection.collection? ? :collection : :one_to_one)
317
+ generate_association_writer(association_name, type)
318
+ else
319
+ raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
320
+ end
321
+ end
322
+ end
323
+
324
+ private
325
+
326
+ # Generates a writer method for this association. Serves as a point for
327
+ # accessing the objects in the association. For example, this method
328
+ # could generate the following:
329
+ #
330
+ # def pirate_attributes=(attributes)
331
+ # assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
332
+ # end
333
+ #
334
+ # This redirects the attempts to write objects in an association through
335
+ # the helper methods defined below. Makes it seem like the nested
336
+ # associations are just regular associations.
337
+ def generate_association_writer(association_name, type)
338
+ generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
339
+ if method_defined?(:#{association_name}_attributes=)
340
+ remove_method(:#{association_name}_attributes=)
341
+ end
342
+ def #{association_name}_attributes=(attributes)
343
+ assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
344
+ end
345
+ eoruby
346
+ end
347
+ end
348
+
349
+ # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
350
+ # used in conjunction with fields_for to build a form element for the
351
+ # destruction of this association.
352
+ #
353
+ # See ActionView::Helpers::FormHelper::fields_for for more info.
354
+ def _destroy
355
+ marked_for_destruction?
356
+ end
357
+
358
+ private
359
+
360
+ # Attribute hash keys that should not be assigned as normal attributes.
361
+ # These hash keys are nested attributes implementation details.
362
+ UNASSIGNABLE_KEYS = %w( id _destroy )
363
+
364
+ # Assigns the given attributes to the association.
365
+ #
366
+ # If an associated record does not yet exist, one will be instantiated. If
367
+ # an associated record already exists, the method's behavior depends on
368
+ # the value of the update_only option. If update_only is +false+ and the
369
+ # given attributes include an <tt>:id</tt> that matches the existing record's
370
+ # id, then the existing record will be modified. If no <tt>:id</tt> is provided
371
+ # it will be replaced with a new record. If update_only is +true+ the existing
372
+ # record will be modified regardless of whether an <tt>:id</tt> is provided.
373
+ #
374
+ # If the given attributes include a matching <tt>:id</tt> attribute, or
375
+ # update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
376
+ # then the existing record will be marked for destruction.
377
+ def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
378
+ options = self.nested_attributes_options[association_name]
379
+ attributes = attributes.with_indifferent_access
380
+ existing_record = send(association_name)
381
+
382
+ if (options[:update_only] || !attributes['id'].blank?) && existing_record &&
383
+ (options[:update_only] || existing_record.id.to_s == attributes['id'].to_s)
384
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
385
+
386
+ elsif attributes['id'].present?
387
+ raise_nested_attributes_record_not_found!(association_name, attributes['id'])
388
+
389
+ elsif !reject_new_record?(association_name, attributes)
390
+ assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS)
391
+
392
+ if existing_record && existing_record.new_record?
393
+ existing_record.assign_attributes(assignable_attributes)
394
+ association(association_name).initialize_attributes(existing_record)
395
+ else
396
+ method = "build_#{association_name}"
397
+ if respond_to?(method)
398
+ send(method, assignable_attributes)
399
+ else
400
+ raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
401
+ end
402
+ end
403
+ end
404
+ end
405
+
406
+ # Assigns the given attributes to the collection association.
407
+ #
408
+ # Hashes with an <tt>:id</tt> value matching an existing associated record
409
+ # will update that record. Hashes without an <tt>:id</tt> value will build
410
+ # a new record for the association. Hashes with a matching <tt>:id</tt>
411
+ # value and a <tt>:_destroy</tt> key set to a truthy value will mark the
412
+ # matched record for destruction.
413
+ #
414
+ # For example:
415
+ #
416
+ # assign_nested_attributes_for_collection_association(:people, {
417
+ # '1' => { id: '1', name: 'Peter' },
418
+ # '2' => { name: 'John' },
419
+ # '3' => { id: '2', _destroy: true }
420
+ # })
421
+ #
422
+ # Will update the name of the Person with ID 1, build a new associated
423
+ # person with the name 'John', and mark the associated Person with ID 2
424
+ # for destruction.
425
+ #
426
+ # Also accepts an Array of attribute hashes:
427
+ #
428
+ # assign_nested_attributes_for_collection_association(:people, [
429
+ # { id: '1', name: 'Peter' },
430
+ # { name: 'John' },
431
+ # { id: '2', _destroy: true }
432
+ # ])
433
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
434
+ options = self.nested_attributes_options[association_name]
435
+
436
+ unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
437
+ raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
438
+ end
439
+
440
+ check_record_limit!(options[:limit], attributes_collection)
441
+
442
+ if attributes_collection.is_a? Hash
443
+ keys = attributes_collection.keys
444
+ attributes_collection = if keys.include?('id') || keys.include?(:id)
445
+ [attributes_collection]
446
+ else
447
+ attributes_collection.values
448
+ end
449
+ end
450
+
451
+ association = association(association_name)
452
+
453
+ existing_records = if association.loaded?
454
+ association.target
455
+ else
456
+ attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
457
+ attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
458
+ end
459
+
460
+ attributes_collection.each do |attributes|
461
+ attributes = attributes.with_indifferent_access
462
+
463
+ if attributes['id'].blank?
464
+ unless reject_new_record?(association_name, attributes)
465
+ association.build(attributes.except(*UNASSIGNABLE_KEYS))
466
+ end
467
+ elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
468
+ unless call_reject_if(association_name, attributes)
469
+ # Make sure we are operating on the actual object which is in the association's
470
+ # proxy_target array (either by finding it, or adding it if not found)
471
+ # Take into account that the proxy_target may have changed due to callbacks
472
+ target_record = association.target.detect { |record| record.id.to_s == attributes['id'].to_s }
473
+ if target_record
474
+ existing_record = target_record
475
+ else
476
+ association.add_to_target(existing_record, :skip_callbacks)
477
+ end
478
+
479
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
480
+ end
481
+ else
482
+ raise_nested_attributes_record_not_found!(association_name, attributes['id'])
483
+ end
484
+ end
485
+ end
486
+
487
+ # Takes in a limit and checks if the attributes_collection has too many
488
+ # records. It accepts limit in the form of symbol, proc, or
489
+ # number-like object (anything that can be compared with an integer).
490
+ #
491
+ # Raises TooManyRecords error if the attributes_collection is
492
+ # larger than the limit.
493
+ def check_record_limit!(limit, attributes_collection)
494
+ if limit
495
+ limit = case limit
496
+ when Symbol
497
+ send(limit)
498
+ when Proc
499
+ limit.call
500
+ else
501
+ limit
502
+ end
503
+
504
+ if limit && attributes_collection.size > limit
505
+ raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
506
+ end
507
+ end
508
+ end
509
+
510
+ # Updates a record with the +attributes+ or marks it for destruction if
511
+ # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
512
+ def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
513
+ record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
514
+ record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
515
+ end
516
+
517
+ # Determines if a hash contains a truthy _destroy key.
518
+ def has_destroy_flag?(hash)
519
+ Type::Boolean.new.type_cast_from_user(hash['_destroy'])
520
+ end
521
+
522
+ # Determines if a new record should be rejected by checking
523
+ # has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
524
+ # association and evaluates to +true+.
525
+ def reject_new_record?(association_name, attributes)
526
+ has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
527
+ end
528
+
529
+ # Determines if a record with the particular +attributes+ should be
530
+ # rejected by calling the reject_if Symbol or Proc (if defined).
531
+ # The reject_if option is defined by +accepts_nested_attributes_for+.
532
+ #
533
+ # Returns false if there is a +destroy_flag+ on the attributes.
534
+ def call_reject_if(association_name, attributes)
535
+ return false if has_destroy_flag?(attributes)
536
+ case callback = self.nested_attributes_options[association_name][:reject_if]
537
+ when Symbol
538
+ method(callback).arity == 0 ? send(callback) : send(callback, attributes)
539
+ when Proc
540
+ callback.call(attributes)
541
+ end
542
+ end
543
+
544
+ def raise_nested_attributes_record_not_found!(association_name, record_id)
545
+ 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}"
546
+ end
547
+ end
548
+ end