activerecord 5.2.3

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