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,439 @@
1
+ module ActiveRecord
2
+ # = Active Record Autosave Association
3
+ #
4
+ # +AutosaveAssociation+ is a module that takes care of automatically saving
5
+ # associated records when their parent is saved. In addition to saving, it
6
+ # also destroys any associated records that were marked for destruction.
7
+ # (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
8
+ #
9
+ # Saving of the parent, its associations, and the destruction of marked
10
+ # associations, all happen inside a transaction. This should never leave the
11
+ # database in an inconsistent state.
12
+ #
13
+ # If validations for any of the associations fail, their error messages will
14
+ # be applied to the parent.
15
+ #
16
+ # Note that it also means that associations marked for destruction won't
17
+ # be destroyed directly. They will however still be marked for destruction.
18
+ #
19
+ # Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>.
20
+ # When the <tt>:autosave</tt> option is not present then new association records are
21
+ # saved but the updated association records are not saved.
22
+ #
23
+ # == Validation
24
+ #
25
+ # Children records are validated unless <tt>:validate</tt> is +false+.
26
+ #
27
+ # == Callbacks
28
+ #
29
+ # Association with autosave option defines several callbacks on your
30
+ # model (before_save, after_create, after_update). Please note that
31
+ # callbacks are executed in the order they were defined in
32
+ # model. You should avoid modifying the association content, before
33
+ # autosave callbacks are executed. Placing your callbacks after
34
+ # associations is usually a good practice.
35
+ #
36
+ # === One-to-one Example
37
+ #
38
+ # class Post < ActiveRecord::Base
39
+ # has_one :author, autosave: true
40
+ # end
41
+ #
42
+ # Saving changes to the parent and its associated model can now be performed
43
+ # automatically _and_ atomically:
44
+ #
45
+ # post = Post.find(1)
46
+ # post.title # => "The current global position of migrating ducks"
47
+ # post.author.name # => "alloy"
48
+ #
49
+ # post.title = "On the migration of ducks"
50
+ # post.author.name = "Eloy Duran"
51
+ #
52
+ # post.save
53
+ # post.reload
54
+ # post.title # => "On the migration of ducks"
55
+ # post.author.name # => "Eloy Duran"
56
+ #
57
+ # Destroying an associated model, as part of the parent's save action, is as
58
+ # simple as marking it for destruction:
59
+ #
60
+ # post.author.mark_for_destruction
61
+ # post.author.marked_for_destruction? # => true
62
+ #
63
+ # Note that the model is _not_ yet removed from the database:
64
+ #
65
+ # id = post.author.id
66
+ # Author.find_by(id: id).nil? # => false
67
+ #
68
+ # post.save
69
+ # post.reload.author # => nil
70
+ #
71
+ # Now it _is_ removed from the database:
72
+ #
73
+ # Author.find_by(id: id).nil? # => true
74
+ #
75
+ # === One-to-many Example
76
+ #
77
+ # When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
78
+ #
79
+ # class Post < ActiveRecord::Base
80
+ # has_many :comments # :autosave option is not declared
81
+ # end
82
+ #
83
+ # post = Post.new(title: 'ruby rocks')
84
+ # post.comments.build(body: 'hello world')
85
+ # post.save # => saves both post and comment
86
+ #
87
+ # post = Post.create(title: 'ruby rocks')
88
+ # post.comments.build(body: 'hello world')
89
+ # post.save # => saves both post and comment
90
+ #
91
+ # post = Post.create(title: 'ruby rocks')
92
+ # post.comments.create(body: 'hello world')
93
+ # post.save # => saves both post and comment
94
+ #
95
+ # When <tt>:autosave</tt> is true all children are saved, no matter whether they
96
+ # are new records or not:
97
+ #
98
+ # class Post < ActiveRecord::Base
99
+ # has_many :comments, autosave: true
100
+ # end
101
+ #
102
+ # post = Post.create(title: 'ruby rocks')
103
+ # post.comments.create(body: 'hello world')
104
+ # post.comments[0].body = 'hi everyone'
105
+ # post.comments.build(body: "good morning.")
106
+ # post.title += "!"
107
+ # post.save # => saves both post and comments.
108
+ #
109
+ # Destroying one of the associated models as part of the parent's save action
110
+ # is as simple as marking it for destruction:
111
+ #
112
+ # post.comments # => [#<Comment id: 1, ...>, #<Comment id: 2, ...]>
113
+ # post.comments[1].mark_for_destruction
114
+ # post.comments[1].marked_for_destruction? # => true
115
+ # post.comments.length # => 2
116
+ #
117
+ # Note that the model is _not_ yet removed from the database:
118
+ #
119
+ # id = post.comments.last.id
120
+ # Comment.find_by(id: id).nil? # => false
121
+ #
122
+ # post.save
123
+ # post.reload.comments.length # => 1
124
+ #
125
+ # Now it _is_ removed from the database:
126
+ #
127
+ # Comment.find_by(id: id).nil? # => true
128
+
129
+ module AutosaveAssociation
130
+ extend ActiveSupport::Concern
131
+
132
+ module AssociationBuilderExtension #:nodoc:
133
+ def self.build(model, reflection)
134
+ model.send(:add_autosave_association_callbacks, reflection)
135
+ end
136
+
137
+ def self.valid_options
138
+ [ :autosave ]
139
+ end
140
+ end
141
+
142
+ included do
143
+ Associations::Builder::Association.extensions << AssociationBuilderExtension
144
+ end
145
+
146
+ module ClassMethods
147
+ private
148
+
149
+ def define_non_cyclic_method(name, &block)
150
+ return if method_defined?(name)
151
+ define_method(name) do |*args|
152
+ result = true; @_already_called ||= {}
153
+ # Loop prevention for validation of associations
154
+ unless @_already_called[name]
155
+ begin
156
+ @_already_called[name]=true
157
+ result = instance_eval(&block)
158
+ ensure
159
+ @_already_called[name]=false
160
+ end
161
+ end
162
+
163
+ result
164
+ end
165
+ end
166
+
167
+ # Adds validation and save callbacks for the association as specified by
168
+ # the +reflection+.
169
+ #
170
+ # For performance reasons, we don't check whether to validate at runtime.
171
+ # However the validation and callback methods are lazy and those methods
172
+ # get created when they are invoked for the very first time. However,
173
+ # this can change, for instance, when using nested attributes, which is
174
+ # called _after_ the association has been defined. Since we don't want
175
+ # the callbacks to get defined multiple times, there are guards that
176
+ # check if the save or validation methods have already been defined
177
+ # before actually defining them.
178
+ def add_autosave_association_callbacks(reflection)
179
+ save_method = :"autosave_associated_records_for_#{reflection.name}"
180
+ validation_method = :"validate_associated_records_for_#{reflection.name}"
181
+ collection = reflection.collection?
182
+
183
+ if collection
184
+ before_save :before_save_collection_association
185
+
186
+ define_non_cyclic_method(save_method) { save_collection_association(reflection) }
187
+ # Doesn't use after_save as that would save associations added in after_create/after_update twice
188
+ after_create save_method
189
+ after_update save_method
190
+ elsif reflection.has_one?
191
+ define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method)
192
+ # Configures two callbacks instead of a single after_save so that
193
+ # the model may rely on their execution order relative to its
194
+ # own callbacks.
195
+ #
196
+ # For example, given that after_creates run before after_saves, if
197
+ # we configured instead an after_save there would be no way to fire
198
+ # a custom after_create callback after the child association gets
199
+ # created.
200
+ after_create save_method
201
+ after_update save_method
202
+ else
203
+ define_non_cyclic_method(save_method) { save_belongs_to_association(reflection) }
204
+ before_save save_method
205
+ end
206
+
207
+ if reflection.validate? && !method_defined?(validation_method)
208
+ method = (collection ? :validate_collection_association : :validate_single_association)
209
+ define_non_cyclic_method(validation_method) { send(method, reflection) }
210
+ validate validation_method
211
+ end
212
+ end
213
+ end
214
+
215
+ # Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
216
+ def reload(options = nil)
217
+ @marked_for_destruction = false
218
+ @destroyed_by_association = nil
219
+ super
220
+ end
221
+
222
+ # Marks this record to be destroyed as part of the parents save transaction.
223
+ # This does _not_ actually destroy the record instantly, rather child record will be destroyed
224
+ # when <tt>parent.save</tt> is called.
225
+ #
226
+ # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
227
+ def mark_for_destruction
228
+ @marked_for_destruction = true
229
+ end
230
+
231
+ # Returns whether or not this record will be destroyed as part of the parents save transaction.
232
+ #
233
+ # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
234
+ def marked_for_destruction?
235
+ @marked_for_destruction
236
+ end
237
+
238
+ # Records the association that is being destroyed and destroying this
239
+ # record in the process.
240
+ def destroyed_by_association=(reflection)
241
+ @destroyed_by_association = reflection
242
+ end
243
+
244
+ # Returns the association for the parent being destroyed.
245
+ #
246
+ # Used to avoid updating the counter cache unnecessarily.
247
+ def destroyed_by_association
248
+ @destroyed_by_association
249
+ end
250
+
251
+ # Returns whether or not this record has been changed in any way (including whether
252
+ # any of its nested autosave associations are likewise changed)
253
+ def changed_for_autosave?
254
+ new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
255
+ end
256
+
257
+ private
258
+
259
+ # Returns the record for an association collection that should be validated
260
+ # or saved. If +autosave+ is +false+ only new records will be returned,
261
+ # unless the parent is/was a new record itself.
262
+ def associated_records_to_validate_or_save(association, new_record, autosave)
263
+ if new_record
264
+ association && association.target
265
+ elsif autosave
266
+ association.target.find_all { |record| record.changed_for_autosave? }
267
+ else
268
+ association.target.find_all { |record| record.new_record? }
269
+ end
270
+ end
271
+
272
+ # go through nested autosave associations that are loaded in memory (without loading
273
+ # any new ones), and return true if is changed for autosave
274
+ def nested_records_changed_for_autosave?
275
+ self.class._reflections.values.any? do |reflection|
276
+ if reflection.options[:autosave]
277
+ association = association_instance_get(reflection.name)
278
+ association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
279
+ end
280
+ end
281
+ end
282
+
283
+ # Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
284
+ # turned on for the association.
285
+ def validate_single_association(reflection)
286
+ association = association_instance_get(reflection.name)
287
+ record = association && association.reader
288
+ association_valid?(reflection, record) if record
289
+ end
290
+
291
+ # Validate the associated records if <tt>:validate</tt> or
292
+ # <tt>:autosave</tt> is turned on for the association specified by
293
+ # +reflection+.
294
+ def validate_collection_association(reflection)
295
+ if association = association_instance_get(reflection.name)
296
+ if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
297
+ records.each { |record| association_valid?(reflection, record) }
298
+ end
299
+ end
300
+ end
301
+
302
+ # Returns whether or not the association is valid and applies any errors to
303
+ # the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
304
+ # enabled records if they're marked_for_destruction? or destroyed.
305
+ def association_valid?(reflection, record)
306
+ return true if record.destroyed? || record.marked_for_destruction?
307
+
308
+ validation_context = self.validation_context unless [:create, :update].include?(self.validation_context)
309
+ unless valid = record.valid?(validation_context)
310
+ if reflection.options[:autosave]
311
+ record.errors.each do |attribute, message|
312
+ attribute = "#{reflection.name}.#{attribute}"
313
+ errors[attribute] << message
314
+ errors[attribute].uniq!
315
+ end
316
+ else
317
+ errors.add(reflection.name)
318
+ end
319
+ end
320
+ valid
321
+ end
322
+
323
+ # Is used as a before_save callback to check while saving a collection
324
+ # association whether or not the parent was a new record before saving.
325
+ def before_save_collection_association
326
+ @new_record_before_save = new_record?
327
+ true
328
+ end
329
+
330
+ # Saves any new associated records, or all loaded autosave associations if
331
+ # <tt>:autosave</tt> is enabled on the association.
332
+ #
333
+ # In addition, it destroys all children that were marked for destruction
334
+ # with mark_for_destruction.
335
+ #
336
+ # This all happens inside a transaction, _if_ the Transactions module is included into
337
+ # ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
338
+ def save_collection_association(reflection)
339
+ if association = association_instance_get(reflection.name)
340
+ autosave = reflection.options[:autosave]
341
+
342
+ if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
343
+ if autosave
344
+ records_to_destroy = records.select(&:marked_for_destruction?)
345
+ records_to_destroy.each { |record| association.destroy(record) }
346
+ records -= records_to_destroy
347
+ end
348
+
349
+ records.each do |record|
350
+ next if record.destroyed?
351
+
352
+ saved = true
353
+
354
+ if autosave != false && (@new_record_before_save || record.new_record?)
355
+ if autosave
356
+ saved = association.insert_record(record, false)
357
+ else
358
+ association.insert_record(record) unless reflection.nested?
359
+ end
360
+ elsif autosave
361
+ saved = record.save(:validate => false)
362
+ end
363
+
364
+ raise ActiveRecord::Rollback unless saved
365
+ end
366
+ end
367
+
368
+ # reconstruct the scope now that we know the owner's id
369
+ association.reset_scope if association.respond_to?(:reset_scope)
370
+ end
371
+ end
372
+
373
+ # Saves the associated record if it's new or <tt>:autosave</tt> is enabled
374
+ # on the association.
375
+ #
376
+ # In addition, it will destroy the association if it was marked for
377
+ # destruction with mark_for_destruction.
378
+ #
379
+ # This all happens inside a transaction, _if_ the Transactions module is included into
380
+ # ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
381
+ def save_has_one_association(reflection)
382
+ association = association_instance_get(reflection.name)
383
+ record = association && association.load_target
384
+
385
+ if record && !record.destroyed?
386
+ autosave = reflection.options[:autosave]
387
+
388
+ if autosave && record.marked_for_destruction?
389
+ record.destroy
390
+ elsif autosave != false
391
+ key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
392
+
393
+ if (autosave && record.changed_for_autosave?) || new_record? || record_changed?(reflection, record, key)
394
+ unless reflection.through_reflection
395
+ record[reflection.foreign_key] = key
396
+ end
397
+
398
+ saved = record.save(:validate => !autosave)
399
+ raise ActiveRecord::Rollback if !saved && autosave
400
+ saved
401
+ end
402
+ end
403
+ end
404
+ end
405
+
406
+ # If the record is new or it has changed, returns true.
407
+ def record_changed?(reflection, record, key)
408
+ record.new_record? ||
409
+ (record.has_attribute?(reflection.foreign_key) && record[reflection.foreign_key] != key) ||
410
+ record.attribute_changed?(reflection.foreign_key)
411
+ end
412
+
413
+ # Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
414
+ #
415
+ # In addition, it will destroy the association if it was marked for destruction.
416
+ def save_belongs_to_association(reflection)
417
+ association = association_instance_get(reflection.name)
418
+ record = association && association.load_target
419
+ if record && !record.destroyed?
420
+ autosave = reflection.options[:autosave]
421
+
422
+ if autosave && record.marked_for_destruction?
423
+ self[reflection.foreign_key] = nil
424
+ record.destroy
425
+ elsif autosave != false
426
+ saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
427
+
428
+ if association.updated?
429
+ association_id = record.send(reflection.options[:primary_key] || :id)
430
+ self[reflection.foreign_key] = association_id
431
+ association.loaded!
432
+ end
433
+
434
+ saved if autosave
435
+ end
436
+ end
437
+ end
438
+ end
439
+ end
@@ -0,0 +1,317 @@
1
+ require 'yaml'
2
+ require 'set'
3
+ require 'active_support/benchmarkable'
4
+ require 'active_support/dependencies'
5
+ require 'active_support/descendants_tracker'
6
+ require 'active_support/time'
7
+ require 'active_support/core_ext/module/attribute_accessors'
8
+ require 'active_support/core_ext/class/delegating_attributes'
9
+ require 'active_support/core_ext/array/extract_options'
10
+ require 'active_support/core_ext/hash/deep_merge'
11
+ require 'active_support/core_ext/hash/slice'
12
+ require 'active_support/core_ext/hash/transform_values'
13
+ require 'active_support/core_ext/string/behavior'
14
+ require 'active_support/core_ext/kernel/singleton_class'
15
+ require 'active_support/core_ext/module/introspection'
16
+ require 'active_support/core_ext/object/duplicable'
17
+ require 'active_support/core_ext/class/subclasses'
18
+ require 'arel'
19
+ require 'active_record/attribute_decorators'
20
+ require 'active_record/errors'
21
+ require 'active_record/log_subscriber'
22
+ require 'active_record/explain_subscriber'
23
+ require 'active_record/relation/delegation'
24
+ require 'active_record/attributes'
25
+
26
+ module ActiveRecord #:nodoc:
27
+ # = Active Record
28
+ #
29
+ # Active Record objects don't specify their attributes directly, but rather infer them from
30
+ # the table definition with which they're linked. Adding, removing, and changing attributes
31
+ # and their type is done directly in the database. Any change is instantly reflected in the
32
+ # Active Record objects. The mapping that binds a given Active Record class to a certain
33
+ # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
34
+ #
35
+ # See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
36
+ #
37
+ # == Creation
38
+ #
39
+ # Active Records accept constructor parameters either in a hash or as a block. The hash
40
+ # method is especially useful when you're receiving the data from somewhere else, like an
41
+ # HTTP request. It works like this:
42
+ #
43
+ # user = User.new(name: "David", occupation: "Code Artist")
44
+ # user.name # => "David"
45
+ #
46
+ # You can also use block initialization:
47
+ #
48
+ # user = User.new do |u|
49
+ # u.name = "David"
50
+ # u.occupation = "Code Artist"
51
+ # end
52
+ #
53
+ # And of course you can just create a bare object and specify the attributes after the fact:
54
+ #
55
+ # user = User.new
56
+ # user.name = "David"
57
+ # user.occupation = "Code Artist"
58
+ #
59
+ # == Conditions
60
+ #
61
+ # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
62
+ # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
63
+ # be used for statements that don't involve tainted data. The hash form works much like the array form, except
64
+ # only equality and range is possible. Examples:
65
+ #
66
+ # class User < ActiveRecord::Base
67
+ # def self.authenticate_unsafely(user_name, password)
68
+ # where("user_name = '#{user_name}' AND password = '#{password}'").first
69
+ # end
70
+ #
71
+ # def self.authenticate_safely(user_name, password)
72
+ # where("user_name = ? AND password = ?", user_name, password).first
73
+ # end
74
+ #
75
+ # def self.authenticate_safely_simply(user_name, password)
76
+ # where(user_name: user_name, password: password).first
77
+ # end
78
+ # end
79
+ #
80
+ # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
81
+ # and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
82
+ # parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
83
+ # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
84
+ # before inserting them in the query, which will ensure that an attacker can't escape the
85
+ # query and fake the login (or worse).
86
+ #
87
+ # When using multiple parameters in the conditions, it can easily become hard to read exactly
88
+ # what the fourth or fifth question mark is supposed to represent. In those cases, you can
89
+ # resort to named bind variables instead. That's done by replacing the question marks with
90
+ # symbols and supplying a hash with values for the matching symbol keys:
91
+ #
92
+ # Company.where(
93
+ # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
94
+ # { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
95
+ # ).first
96
+ #
97
+ # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
98
+ # operator. For instance:
99
+ #
100
+ # Student.where(first_name: "Harvey", status: 1)
101
+ # Student.where(params[:student])
102
+ #
103
+ # A range may be used in the hash to use the SQL BETWEEN operator:
104
+ #
105
+ # Student.where(grade: 9..12)
106
+ #
107
+ # An array may be used in the hash to use the SQL IN operator:
108
+ #
109
+ # Student.where(grade: [9,11,12])
110
+ #
111
+ # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
112
+ # can be used to qualify the table name of a particular condition. For instance:
113
+ #
114
+ # Student.joins(:schools).where(schools: { category: 'public' })
115
+ # Student.joins(:schools).where('schools.category' => 'public' )
116
+ #
117
+ # == Overwriting default accessors
118
+ #
119
+ # All column values are automatically available through basic accessors on the Active Record
120
+ # object, but sometimes you want to specialize this behavior. This can be done by overwriting
121
+ # the default accessors (using the same name as the attribute) and calling
122
+ # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
123
+ # change things.
124
+ #
125
+ # class Song < ActiveRecord::Base
126
+ # # Uses an integer of seconds to hold the length of the song
127
+ #
128
+ # def length=(minutes)
129
+ # write_attribute(:length, minutes.to_i * 60)
130
+ # end
131
+ #
132
+ # def length
133
+ # read_attribute(:length) / 60
134
+ # end
135
+ # end
136
+ #
137
+ # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
138
+ # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
139
+ #
140
+ # == Attribute query methods
141
+ #
142
+ # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
143
+ # Query methods allow you to test whether an attribute value is present.
144
+ # For numeric values, present is defined as non-zero.
145
+ #
146
+ # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
147
+ # to determine whether the user has a name:
148
+ #
149
+ # user = User.new(name: "David")
150
+ # user.name? # => true
151
+ #
152
+ # anonymous = User.new(name: "")
153
+ # anonymous.name? # => false
154
+ #
155
+ # == Accessing attributes before they have been typecasted
156
+ #
157
+ # Sometimes you want to be able to read the raw attribute data without having the column-determined
158
+ # typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
159
+ # accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
160
+ # you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
161
+ #
162
+ # This is especially useful in validation situations where the user might supply a string for an
163
+ # integer field and you want to display the original string back in an error message. Accessing the
164
+ # attribute normally would typecast the string to 0, which isn't what you want.
165
+ #
166
+ # == Dynamic attribute-based finders
167
+ #
168
+ # Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
169
+ # by simple queries without turning to SQL. They work by appending the name of an attribute
170
+ # to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
171
+ # Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
172
+ # <tt>Person.find_by_user_name(user_name)</tt>.
173
+ #
174
+ # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
175
+ # <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
176
+ # like <tt>Person.find_by_last_name!</tt>.
177
+ #
178
+ # It's also possible to use multiple attributes in the same find by separating them with "_and_".
179
+ #
180
+ # Person.find_by(user_name: user_name, password: password)
181
+ # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
182
+ #
183
+ # It's even possible to call these dynamic finder methods on relations and named scopes.
184
+ #
185
+ # Payment.order("created_on").find_by_amount(50)
186
+ #
187
+ # == Saving arrays, hashes, and other non-mappable objects in text columns
188
+ #
189
+ # Active Record can serialize any object in text columns using YAML. To do so, you must
190
+ # specify this with a call to the class method +serialize+.
191
+ # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
192
+ # any additional work.
193
+ #
194
+ # class User < ActiveRecord::Base
195
+ # serialize :preferences
196
+ # end
197
+ #
198
+ # user = User.create(preferences: { "background" => "black", "display" => large })
199
+ # User.find(user.id).preferences # => { "background" => "black", "display" => large }
200
+ #
201
+ # You can also specify a class option as the second parameter that'll raise an exception
202
+ # if a serialized object is retrieved as a descendant of a class not in the hierarchy.
203
+ #
204
+ # class User < ActiveRecord::Base
205
+ # serialize :preferences, Hash
206
+ # end
207
+ #
208
+ # user = User.create(preferences: %w( one two three ))
209
+ # User.find(user.id).preferences # raises SerializationTypeMismatch
210
+ #
211
+ # When you specify a class option, the default value for that attribute will be a new
212
+ # instance of that class.
213
+ #
214
+ # class User < ActiveRecord::Base
215
+ # serialize :preferences, OpenStruct
216
+ # end
217
+ #
218
+ # user = User.new
219
+ # user.preferences.theme_color = "red"
220
+ #
221
+ #
222
+ # == Single table inheritance
223
+ #
224
+ # Active Record allows inheritance by storing the name of the class in a
225
+ # column that is named "type" by default. See ActiveRecord::Inheritance for
226
+ # more details.
227
+ #
228
+ # == Connection to multiple databases in different models
229
+ #
230
+ # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
231
+ # by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
232
+ # connection. But you can also set a class-specific connection. For example, if Course is an
233
+ # ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
234
+ # and Course and all of its subclasses will use this connection instead.
235
+ #
236
+ # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
237
+ # a Hash indexed by the class. If a connection is requested, the retrieve_connection method
238
+ # will go up the class-hierarchy until a connection is found in the connection pool.
239
+ #
240
+ # == Exceptions
241
+ #
242
+ # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
243
+ # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
244
+ # <tt>:adapter</tt> key.
245
+ # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
246
+ # non-existent adapter
247
+ # (or a bad spelling of an existing one).
248
+ # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
249
+ # specified in the association definition.
250
+ # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
251
+ # <tt>attributes=</tt> method.
252
+ # You can inspect the +attribute+ property of the exception object to determine which attribute
253
+ # triggered the error.
254
+ # * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
255
+ # before querying.
256
+ # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
257
+ # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
258
+ # AttributeAssignmentError
259
+ # objects that should be inspected to determine which attributes triggered the errors.
260
+ # * RecordInvalid - raised by save! and create! when the record is invalid.
261
+ # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
262
+ # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
263
+ # nothing was found, please check its documentation for further details.
264
+ # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
265
+ # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
266
+ #
267
+ # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
268
+ # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
269
+ # instances in the current object space.
270
+ class Base
271
+ extend ActiveModel::Naming
272
+
273
+ extend ActiveSupport::Benchmarkable
274
+ extend ActiveSupport::DescendantsTracker
275
+
276
+ extend ConnectionHandling
277
+ extend QueryCache::ClassMethods
278
+ extend Querying
279
+ extend Translation
280
+ extend DynamicMatchers
281
+ extend Explain
282
+ extend Enum
283
+ extend Delegation::DelegateCache
284
+
285
+ include Core
286
+ include Persistence
287
+ include ReadonlyAttributes
288
+ include ModelSchema
289
+ include Inheritance
290
+ include Scoping
291
+ include Sanitization
292
+ include AttributeAssignment
293
+ include ActiveModel::Conversion
294
+ include Integration
295
+ include Validations
296
+ include CounterCache
297
+ include Attributes
298
+ include AttributeDecorators
299
+ include Locking::Optimistic
300
+ include Locking::Pessimistic
301
+ include AttributeMethods
302
+ include Callbacks
303
+ include Timestamp
304
+ include Associations
305
+ include ActiveModel::SecurePassword
306
+ include AutosaveAssociation
307
+ include NestedAttributes
308
+ include Aggregations
309
+ include Transactions
310
+ include NoTouching
311
+ include Reflection
312
+ include Serialization
313
+ include Store
314
+ end
315
+
316
+ ActiveSupport.run_load_hooks(:active_record, Base)
317
+ end