activerecord 1.0.0 → 4.0.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 (255) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +2102 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +213 -0
  5. data/examples/performance.rb +172 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record/aggregations.rb +180 -84
  8. data/lib/active_record/associations/alias_tracker.rb +76 -0
  9. data/lib/active_record/associations/association.rb +248 -0
  10. data/lib/active_record/associations/association_scope.rb +135 -0
  11. data/lib/active_record/associations/belongs_to_association.rb +92 -0
  12. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +35 -0
  13. data/lib/active_record/associations/builder/association.rb +108 -0
  14. data/lib/active_record/associations/builder/belongs_to.rb +98 -0
  15. data/lib/active_record/associations/builder/collection_association.rb +89 -0
  16. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +39 -0
  17. data/lib/active_record/associations/builder/has_many.rb +15 -0
  18. data/lib/active_record/associations/builder/has_one.rb +25 -0
  19. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  20. data/lib/active_record/associations/collection_association.rb +608 -0
  21. data/lib/active_record/associations/collection_proxy.rb +986 -0
  22. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +58 -39
  23. data/lib/active_record/associations/has_many_association.rb +116 -85
  24. data/lib/active_record/associations/has_many_through_association.rb +197 -0
  25. data/lib/active_record/associations/has_one_association.rb +102 -0
  26. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  27. data/lib/active_record/associations/join_dependency/join_association.rb +174 -0
  28. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  29. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  30. data/lib/active_record/associations/join_dependency.rb +235 -0
  31. data/lib/active_record/associations/join_helper.rb +45 -0
  32. data/lib/active_record/associations/preloader/association.rb +121 -0
  33. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  34. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  35. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  36. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  37. data/lib/active_record/associations/preloader/has_many_through.rb +19 -0
  38. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  39. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  40. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  41. data/lib/active_record/associations/preloader/through_association.rb +63 -0
  42. data/lib/active_record/associations/preloader.rb +178 -0
  43. data/lib/active_record/associations/singular_association.rb +64 -0
  44. data/lib/active_record/associations/through_association.rb +87 -0
  45. data/lib/active_record/associations.rb +1437 -431
  46. data/lib/active_record/attribute_assignment.rb +201 -0
  47. data/lib/active_record/attribute_methods/before_type_cast.rb +70 -0
  48. data/lib/active_record/attribute_methods/dirty.rb +118 -0
  49. data/lib/active_record/attribute_methods/primary_key.rb +122 -0
  50. data/lib/active_record/attribute_methods/query.rb +40 -0
  51. data/lib/active_record/attribute_methods/read.rb +107 -0
  52. data/lib/active_record/attribute_methods/serialization.rb +162 -0
  53. data/lib/active_record/attribute_methods/time_zone_conversion.rb +59 -0
  54. data/lib/active_record/attribute_methods/write.rb +63 -0
  55. data/lib/active_record/attribute_methods.rb +393 -0
  56. data/lib/active_record/autosave_association.rb +426 -0
  57. data/lib/active_record/base.rb +268 -930
  58. data/lib/active_record/callbacks.rb +203 -230
  59. data/lib/active_record/coders/yaml_column.rb +38 -0
  60. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +638 -0
  61. data/lib/active_record/connection_adapters/abstract/database_limits.rb +67 -0
  62. data/lib/active_record/connection_adapters/abstract/database_statements.rb +390 -0
  63. data/lib/active_record/connection_adapters/abstract/query_cache.rb +95 -0
  64. data/lib/active_record/connection_adapters/abstract/quoting.rb +129 -0
  65. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +501 -0
  66. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +70 -0
  67. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +873 -0
  68. data/lib/active_record/connection_adapters/abstract/transaction.rb +203 -0
  69. data/lib/active_record/connection_adapters/abstract_adapter.rb +389 -275
  70. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +782 -0
  71. data/lib/active_record/connection_adapters/column.rb +318 -0
  72. data/lib/active_record/connection_adapters/connection_specification.rb +96 -0
  73. data/lib/active_record/connection_adapters/mysql2_adapter.rb +273 -0
  74. data/lib/active_record/connection_adapters/mysql_adapter.rb +517 -90
  75. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +97 -0
  76. data/lib/active_record/connection_adapters/postgresql/cast.rb +152 -0
  77. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +242 -0
  78. data/lib/active_record/connection_adapters/postgresql/oid.rb +366 -0
  79. data/lib/active_record/connection_adapters/postgresql/quoting.rb +171 -0
  80. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  81. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +489 -0
  82. data/lib/active_record/connection_adapters/postgresql_adapter.rb +911 -138
  83. data/lib/active_record/connection_adapters/schema_cache.rb +129 -0
  84. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +624 -0
  85. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  86. data/lib/active_record/connection_handling.rb +98 -0
  87. data/lib/active_record/core.rb +463 -0
  88. data/lib/active_record/counter_cache.rb +122 -0
  89. data/lib/active_record/dynamic_matchers.rb +131 -0
  90. data/lib/active_record/errors.rb +213 -0
  91. data/lib/active_record/explain.rb +38 -0
  92. data/lib/active_record/explain_registry.rb +30 -0
  93. data/lib/active_record/explain_subscriber.rb +29 -0
  94. data/lib/active_record/fixture_set/file.rb +55 -0
  95. data/lib/active_record/fixtures.rb +892 -138
  96. data/lib/active_record/inheritance.rb +200 -0
  97. data/lib/active_record/integration.rb +60 -0
  98. data/lib/active_record/locale/en.yml +47 -0
  99. data/lib/active_record/locking/optimistic.rb +181 -0
  100. data/lib/active_record/locking/pessimistic.rb +77 -0
  101. data/lib/active_record/log_subscriber.rb +82 -0
  102. data/lib/active_record/migration/command_recorder.rb +164 -0
  103. data/lib/active_record/migration/join_table.rb +15 -0
  104. data/lib/active_record/migration.rb +1015 -0
  105. data/lib/active_record/model_schema.rb +345 -0
  106. data/lib/active_record/nested_attributes.rb +546 -0
  107. data/lib/active_record/null_relation.rb +65 -0
  108. data/lib/active_record/persistence.rb +509 -0
  109. data/lib/active_record/query_cache.rb +56 -0
  110. data/lib/active_record/querying.rb +62 -0
  111. data/lib/active_record/railtie.rb +205 -0
  112. data/lib/active_record/railties/console_sandbox.rb +5 -0
  113. data/lib/active_record/railties/controller_runtime.rb +50 -0
  114. data/lib/active_record/railties/databases.rake +402 -0
  115. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  116. data/lib/active_record/readonly_attributes.rb +30 -0
  117. data/lib/active_record/reflection.rb +544 -87
  118. data/lib/active_record/relation/batches.rb +93 -0
  119. data/lib/active_record/relation/calculations.rb +399 -0
  120. data/lib/active_record/relation/delegation.rb +125 -0
  121. data/lib/active_record/relation/finder_methods.rb +349 -0
  122. data/lib/active_record/relation/merger.rb +161 -0
  123. data/lib/active_record/relation/predicate_builder.rb +106 -0
  124. data/lib/active_record/relation/query_methods.rb +1044 -0
  125. data/lib/active_record/relation/spawn_methods.rb +73 -0
  126. data/lib/active_record/relation.rb +655 -0
  127. data/lib/active_record/result.rb +67 -0
  128. data/lib/active_record/runtime_registry.rb +17 -0
  129. data/lib/active_record/sanitization.rb +168 -0
  130. data/lib/active_record/schema.rb +65 -0
  131. data/lib/active_record/schema_dumper.rb +204 -0
  132. data/lib/active_record/schema_migration.rb +39 -0
  133. data/lib/active_record/scoping/default.rb +146 -0
  134. data/lib/active_record/scoping/named.rb +175 -0
  135. data/lib/active_record/scoping.rb +82 -0
  136. data/lib/active_record/serialization.rb +22 -0
  137. data/lib/active_record/serializers/xml_serializer.rb +197 -0
  138. data/lib/active_record/statement_cache.rb +26 -0
  139. data/lib/active_record/store.rb +156 -0
  140. data/lib/active_record/tasks/database_tasks.rb +203 -0
  141. data/lib/active_record/tasks/firebird_database_tasks.rb +56 -0
  142. data/lib/active_record/tasks/mysql_database_tasks.rb +143 -0
  143. data/lib/active_record/tasks/oracle_database_tasks.rb +45 -0
  144. data/lib/active_record/tasks/postgresql_database_tasks.rb +90 -0
  145. data/lib/active_record/tasks/sqlite_database_tasks.rb +51 -0
  146. data/lib/active_record/tasks/sqlserver_database_tasks.rb +48 -0
  147. data/lib/active_record/test_case.rb +96 -0
  148. data/lib/active_record/timestamp.rb +119 -0
  149. data/lib/active_record/transactions.rb +366 -69
  150. data/lib/active_record/translation.rb +22 -0
  151. data/lib/active_record/validations/associated.rb +49 -0
  152. data/lib/active_record/validations/presence.rb +65 -0
  153. data/lib/active_record/validations/uniqueness.rb +225 -0
  154. data/lib/active_record/validations.rb +64 -185
  155. data/lib/active_record/version.rb +11 -0
  156. data/lib/active_record.rb +149 -24
  157. data/lib/rails/generators/active_record/migration/migration_generator.rb +62 -0
  158. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +19 -0
  159. data/lib/rails/generators/active_record/migration/templates/migration.rb +39 -0
  160. data/lib/rails/generators/active_record/model/model_generator.rb +48 -0
  161. data/lib/rails/generators/active_record/model/templates/model.rb +10 -0
  162. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  163. data/lib/rails/generators/active_record.rb +23 -0
  164. metadata +261 -161
  165. data/CHANGELOG +0 -581
  166. data/README +0 -361
  167. data/RUNNING_UNIT_TESTS +0 -36
  168. data/dev-utils/eval_debugger.rb +0 -9
  169. data/examples/associations.png +0 -0
  170. data/examples/associations.rb +0 -87
  171. data/examples/shared_setup.rb +0 -15
  172. data/examples/validation.rb +0 -88
  173. data/install.rb +0 -60
  174. data/lib/active_record/associations/association_collection.rb +0 -70
  175. data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -107
  176. data/lib/active_record/deprecated_associations.rb +0 -70
  177. data/lib/active_record/observer.rb +0 -71
  178. data/lib/active_record/support/class_attribute_accessors.rb +0 -43
  179. data/lib/active_record/support/class_inheritable_attributes.rb +0 -37
  180. data/lib/active_record/support/clean_logger.rb +0 -10
  181. data/lib/active_record/support/inflector.rb +0 -70
  182. data/lib/active_record/vendor/mysql.rb +0 -1117
  183. data/lib/active_record/vendor/simple.rb +0 -702
  184. data/lib/active_record/wrappers/yaml_wrapper.rb +0 -15
  185. data/lib/active_record/wrappings.rb +0 -59
  186. data/rakefile +0 -122
  187. data/test/abstract_unit.rb +0 -16
  188. data/test/aggregations_test.rb +0 -34
  189. data/test/all.sh +0 -8
  190. data/test/associations_test.rb +0 -477
  191. data/test/base_test.rb +0 -513
  192. data/test/class_inheritable_attributes_test.rb +0 -33
  193. data/test/connections/native_mysql/connection.rb +0 -24
  194. data/test/connections/native_postgresql/connection.rb +0 -24
  195. data/test/connections/native_sqlite/connection.rb +0 -24
  196. data/test/deprecated_associations_test.rb +0 -336
  197. data/test/finder_test.rb +0 -67
  198. data/test/fixtures/accounts/signals37 +0 -3
  199. data/test/fixtures/accounts/unknown +0 -2
  200. data/test/fixtures/auto_id.rb +0 -4
  201. data/test/fixtures/column_name.rb +0 -3
  202. data/test/fixtures/companies/first_client +0 -6
  203. data/test/fixtures/companies/first_firm +0 -4
  204. data/test/fixtures/companies/second_client +0 -6
  205. data/test/fixtures/company.rb +0 -37
  206. data/test/fixtures/company_in_module.rb +0 -33
  207. data/test/fixtures/course.rb +0 -3
  208. data/test/fixtures/courses/java +0 -2
  209. data/test/fixtures/courses/ruby +0 -2
  210. data/test/fixtures/customer.rb +0 -30
  211. data/test/fixtures/customers/david +0 -6
  212. data/test/fixtures/db_definitions/mysql.sql +0 -96
  213. data/test/fixtures/db_definitions/mysql2.sql +0 -4
  214. data/test/fixtures/db_definitions/postgresql.sql +0 -113
  215. data/test/fixtures/db_definitions/postgresql2.sql +0 -4
  216. data/test/fixtures/db_definitions/sqlite.sql +0 -85
  217. data/test/fixtures/db_definitions/sqlite2.sql +0 -4
  218. data/test/fixtures/default.rb +0 -2
  219. data/test/fixtures/developer.rb +0 -8
  220. data/test/fixtures/developers/david +0 -2
  221. data/test/fixtures/developers/jamis +0 -2
  222. data/test/fixtures/developers_projects/david_action_controller +0 -2
  223. data/test/fixtures/developers_projects/david_active_record +0 -2
  224. data/test/fixtures/developers_projects/jamis_active_record +0 -2
  225. data/test/fixtures/entrant.rb +0 -3
  226. data/test/fixtures/entrants/first +0 -3
  227. data/test/fixtures/entrants/second +0 -3
  228. data/test/fixtures/entrants/third +0 -3
  229. data/test/fixtures/fixture_database.sqlite +0 -0
  230. data/test/fixtures/fixture_database_2.sqlite +0 -0
  231. data/test/fixtures/movie.rb +0 -5
  232. data/test/fixtures/movies/first +0 -2
  233. data/test/fixtures/movies/second +0 -2
  234. data/test/fixtures/project.rb +0 -3
  235. data/test/fixtures/projects/action_controller +0 -2
  236. data/test/fixtures/projects/active_record +0 -2
  237. data/test/fixtures/reply.rb +0 -21
  238. data/test/fixtures/subscriber.rb +0 -5
  239. data/test/fixtures/subscribers/first +0 -2
  240. data/test/fixtures/subscribers/second +0 -2
  241. data/test/fixtures/topic.rb +0 -20
  242. data/test/fixtures/topics/first +0 -9
  243. data/test/fixtures/topics/second +0 -8
  244. data/test/fixtures_test.rb +0 -20
  245. data/test/inflector_test.rb +0 -104
  246. data/test/inheritance_test.rb +0 -125
  247. data/test/lifecycle_test.rb +0 -110
  248. data/test/modules_test.rb +0 -21
  249. data/test/multiple_db_test.rb +0 -46
  250. data/test/pk_test.rb +0 -57
  251. data/test/reflection_test.rb +0 -78
  252. data/test/thread_safety_test.rb +0 -33
  253. data/test/transactions_test.rb +0 -83
  254. data/test/unconnected_test.rb +0 -24
  255. data/test/validations_test.rb +0 -126
@@ -0,0 +1,546 @@
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
+ # For one-to-one nested associations, if you build the new (in-memory)
234
+ # child object yourself before assignment, then this module will not
235
+ # overwrite it, e.g.:
236
+ #
237
+ # class Member < ActiveRecord::Base
238
+ # has_one :avatar
239
+ # accepts_nested_attributes_for :avatar
240
+ #
241
+ # def avatar
242
+ # super || build_avatar(width: 200)
243
+ # end
244
+ # end
245
+ #
246
+ # member = Member.new
247
+ # member.avatar_attributes = {icon: 'sad'}
248
+ # member.avatar.width # => 200
249
+ module ClassMethods
250
+ REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
251
+
252
+ # Defines an attributes writer for the specified association(s).
253
+ #
254
+ # Supported options:
255
+ # [:allow_destroy]
256
+ # If true, destroys any members from the attributes hash with a
257
+ # <tt>_destroy</tt> key and a value that evaluates to +true+
258
+ # (eg. 1, '1', true, or 'true'). This option is off by default.
259
+ # [:reject_if]
260
+ # Allows you to specify a Proc or a Symbol pointing to a method
261
+ # that checks whether a record should be built for a certain attribute
262
+ # hash. The hash is passed to the supplied Proc or the method
263
+ # and it should return either +true+ or +false+. When no :reject_if
264
+ # is specified, a record will be built for all attribute hashes that
265
+ # do not have a <tt>_destroy</tt> value that evaluates to true.
266
+ # Passing <tt>:all_blank</tt> instead of a Proc will create a proc
267
+ # that will reject a record where all the attributes are blank excluding
268
+ # any value for _destroy.
269
+ # [:limit]
270
+ # Allows you to specify the maximum number of the associated records that
271
+ # can be processed with the nested attributes. Limit also can be specified as a
272
+ # Proc or a Symbol pointing to a method that should return number. If the size of the
273
+ # nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
274
+ # exception is raised. If omitted, any number associations can be processed.
275
+ # Note that the :limit option is only applicable to one-to-many associations.
276
+ # [:update_only]
277
+ # For a one-to-one association, this option allows you to specify how
278
+ # nested attributes are to be used when an associated record already
279
+ # exists. In general, an existing record may either be updated with the
280
+ # new set of attribute values or be replaced by a wholly new record
281
+ # containing those values. By default the :update_only option is +false+
282
+ # and the nested attributes are used to update the existing record only
283
+ # if they include the record's <tt>:id</tt> value. Otherwise a new
284
+ # record will be instantiated and used to replace the existing one.
285
+ # However if the :update_only option is +true+, the nested attributes
286
+ # are used to update the record's attributes always, regardless of
287
+ # whether the <tt>:id</tt> is present. The option is ignored for collection
288
+ # associations.
289
+ #
290
+ # Examples:
291
+ # # creates avatar_attributes=
292
+ # accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
293
+ # # creates avatar_attributes=
294
+ # accepts_nested_attributes_for :avatar, reject_if: :all_blank
295
+ # # creates avatar_attributes= and posts_attributes=
296
+ # accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
297
+ def accepts_nested_attributes_for(*attr_names)
298
+ options = { :allow_destroy => false, :update_only => false }
299
+ options.update(attr_names.extract_options!)
300
+ options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
301
+ options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
302
+
303
+ attr_names.each do |association_name|
304
+ if reflection = reflect_on_association(association_name)
305
+ reflection.options[:autosave] = true
306
+ add_autosave_association_callbacks(reflection)
307
+
308
+ nested_attributes_options = self.nested_attributes_options.dup
309
+ nested_attributes_options[association_name.to_sym] = options
310
+ self.nested_attributes_options = nested_attributes_options
311
+
312
+ type = (reflection.collection? ? :collection : :one_to_one)
313
+ generate_association_writer(association_name, type)
314
+ else
315
+ raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
316
+ end
317
+ end
318
+ end
319
+
320
+ private
321
+
322
+ # Generates a writer method for this association. Serves as a point for
323
+ # accessing the objects in the association. For example, this method
324
+ # could generate the following:
325
+ #
326
+ # def pirate_attributes=(attributes)
327
+ # assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
328
+ # end
329
+ #
330
+ # This redirects the attempts to write objects in an association through
331
+ # the helper methods defined below. Makes it seem like the nested
332
+ # associations are just regular associations.
333
+ def generate_association_writer(association_name, type)
334
+ generated_feature_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
335
+ if method_defined?(:#{association_name}_attributes=)
336
+ remove_method(:#{association_name}_attributes=)
337
+ end
338
+ def #{association_name}_attributes=(attributes)
339
+ assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
340
+ end
341
+ eoruby
342
+ end
343
+ end
344
+
345
+ # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
346
+ # used in conjunction with fields_for to build a form element for the
347
+ # destruction of this association.
348
+ #
349
+ # See ActionView::Helpers::FormHelper::fields_for for more info.
350
+ def _destroy
351
+ marked_for_destruction?
352
+ end
353
+
354
+ private
355
+
356
+ # Attribute hash keys that should not be assigned as normal attributes.
357
+ # These hash keys are nested attributes implementation details.
358
+ UNASSIGNABLE_KEYS = %w( id _destroy )
359
+
360
+ # Assigns the given attributes to the association.
361
+ #
362
+ # If an associated record does not yet exist, one will be instantiated. If
363
+ # an associated record already exists, the method's behavior depends on
364
+ # the value of the update_only option. If update_only is +false+ and the
365
+ # given attributes include an <tt>:id</tt> that matches the existing record's
366
+ # id, then the existing record will be modified. If no <tt>:id</tt> is provided
367
+ # it will be replaced with a new record. If update_only is +true+ the existing
368
+ # record will be modified regardless of whether an <tt>:id</tt> is provided.
369
+ #
370
+ # If the given attributes include a matching <tt>:id</tt> attribute, or
371
+ # update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
372
+ # then the existing record will be marked for destruction.
373
+ def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
374
+ options = self.nested_attributes_options[association_name]
375
+ attributes = attributes.with_indifferent_access
376
+ existing_record = send(association_name)
377
+
378
+ if (options[:update_only] || !attributes['id'].blank?) && existing_record &&
379
+ (options[:update_only] || existing_record.id.to_s == attributes['id'].to_s)
380
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
381
+
382
+ elsif attributes['id'].present?
383
+ raise_nested_attributes_record_not_found!(association_name, attributes['id'])
384
+
385
+ elsif !reject_new_record?(association_name, attributes)
386
+ assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS)
387
+
388
+ if existing_record && existing_record.new_record?
389
+ existing_record.assign_attributes(assignable_attributes)
390
+ association(association_name).initialize_attributes(existing_record)
391
+ else
392
+ method = "build_#{association_name}"
393
+ if respond_to?(method)
394
+ send(method, assignable_attributes)
395
+ else
396
+ raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
397
+ end
398
+ end
399
+ end
400
+ end
401
+
402
+ # Assigns the given attributes to the collection association.
403
+ #
404
+ # Hashes with an <tt>:id</tt> value matching an existing associated record
405
+ # will update that record. Hashes without an <tt>:id</tt> value will build
406
+ # a new record for the association. Hashes with a matching <tt>:id</tt>
407
+ # value and a <tt>:_destroy</tt> key set to a truthy value will mark the
408
+ # matched record for destruction.
409
+ #
410
+ # For example:
411
+ #
412
+ # assign_nested_attributes_for_collection_association(:people, {
413
+ # '1' => { id: '1', name: 'Peter' },
414
+ # '2' => { name: 'John' },
415
+ # '3' => { id: '2', _destroy: true }
416
+ # })
417
+ #
418
+ # Will update the name of the Person with ID 1, build a new associated
419
+ # person with the name 'John', and mark the associated Person with ID 2
420
+ # for destruction.
421
+ #
422
+ # Also accepts an Array of attribute hashes:
423
+ #
424
+ # assign_nested_attributes_for_collection_association(:people, [
425
+ # { id: '1', name: 'Peter' },
426
+ # { name: 'John' },
427
+ # { id: '2', _destroy: true }
428
+ # ])
429
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
430
+ options = self.nested_attributes_options[association_name]
431
+
432
+ unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
433
+ raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
434
+ end
435
+
436
+ check_record_limit!(options[:limit], attributes_collection)
437
+
438
+ if attributes_collection.is_a? Hash
439
+ keys = attributes_collection.keys
440
+ attributes_collection = if keys.include?('id') || keys.include?(:id)
441
+ [attributes_collection]
442
+ else
443
+ attributes_collection.values
444
+ end
445
+ end
446
+
447
+ association = association(association_name)
448
+
449
+ existing_records = if association.loaded?
450
+ association.target
451
+ else
452
+ attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
453
+ attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
454
+ end
455
+
456
+ attributes_collection.each do |attributes|
457
+ attributes = attributes.with_indifferent_access
458
+
459
+ if attributes['id'].blank?
460
+ unless reject_new_record?(association_name, attributes)
461
+ association.build(attributes.except(*UNASSIGNABLE_KEYS))
462
+ end
463
+ elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
464
+ unless association.loaded? || call_reject_if(association_name, attributes)
465
+ # Make sure we are operating on the actual object which is in the association's
466
+ # proxy_target array (either by finding it, or adding it if not found)
467
+ target_record = association.target.detect { |record| record == existing_record }
468
+
469
+ if target_record
470
+ existing_record = target_record
471
+ else
472
+ association.add_to_target(existing_record)
473
+ end
474
+ end
475
+
476
+ if !call_reject_if(association_name, attributes)
477
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
478
+ end
479
+ else
480
+ raise_nested_attributes_record_not_found!(association_name, attributes['id'])
481
+ end
482
+ end
483
+ end
484
+
485
+ # Takes in a limit and checks if the attributes_collection has too many
486
+ # records. The method will take limits in the form of symbols, procs, and
487
+ # number-like objects (anything that can be compared with an integer).
488
+ #
489
+ # Will raise an TooManyRecords error if the attributes_collection is
490
+ # larger than the limit.
491
+ def check_record_limit!(limit, attributes_collection)
492
+ if limit
493
+ limit = case limit
494
+ when Symbol
495
+ send(limit)
496
+ when Proc
497
+ limit.call
498
+ else
499
+ limit
500
+ end
501
+
502
+ if limit && attributes_collection.size > limit
503
+ raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
504
+ end
505
+ end
506
+ end
507
+
508
+ # Updates a record with the +attributes+ or marks it for destruction if
509
+ # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
510
+ def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
511
+ record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
512
+ record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
513
+ end
514
+
515
+ # Determines if a hash contains a truthy _destroy key.
516
+ def has_destroy_flag?(hash)
517
+ ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
518
+ end
519
+
520
+ # Determines if a new record should be build by checking for
521
+ # has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
522
+ # association and evaluates to +true+.
523
+ def reject_new_record?(association_name, attributes)
524
+ has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
525
+ end
526
+
527
+ # Determines if a record with the particular +attributes+ should be
528
+ # rejected by calling the reject_if Symbol or Proc (if defined).
529
+ # The reject_if option is defined by +accepts_nested_attributes_for+.
530
+ #
531
+ # Returns false if there is a +destroy_flag+ on the attributes.
532
+ def call_reject_if(association_name, attributes)
533
+ return false if has_destroy_flag?(attributes)
534
+ case callback = self.nested_attributes_options[association_name][:reject_if]
535
+ when Symbol
536
+ method(callback).arity == 0 ? send(callback) : send(callback, attributes)
537
+ when Proc
538
+ callback.call(attributes)
539
+ end
540
+ end
541
+
542
+ def raise_nested_attributes_record_not_found!(association_name, record_id)
543
+ 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}"
544
+ end
545
+ end
546
+ end
@@ -0,0 +1,65 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ module ActiveRecord
4
+ module NullRelation # :nodoc:
5
+ def exec_queries
6
+ @records = []
7
+ end
8
+
9
+ def pluck(_column_name)
10
+ []
11
+ end
12
+
13
+ def delete_all(_conditions = nil)
14
+ 0
15
+ end
16
+
17
+ def update_all(_updates, _conditions = nil, _options = {})
18
+ 0
19
+ end
20
+
21
+ def delete(_id_or_array)
22
+ 0
23
+ end
24
+
25
+ def size
26
+ 0
27
+ end
28
+
29
+ def empty?
30
+ true
31
+ end
32
+
33
+ def any?
34
+ false
35
+ end
36
+
37
+ def many?
38
+ false
39
+ end
40
+
41
+ def to_sql
42
+ @to_sql ||= ""
43
+ end
44
+
45
+ def where_values_hash
46
+ {}
47
+ end
48
+
49
+ def count(*)
50
+ 0
51
+ end
52
+
53
+ def sum(*)
54
+ 0
55
+ end
56
+
57
+ def calculate(_operation, _column_name, _options = {})
58
+ nil
59
+ end
60
+
61
+ def exists?(_id = false)
62
+ false
63
+ end
64
+ end
65
+ end