activerecord 3.2.22.5 → 4.2.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (236) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +1632 -609
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +37 -41
  5. data/examples/performance.rb +31 -19
  6. data/examples/simple.rb +4 -4
  7. data/lib/active_record/aggregations.rb +56 -42
  8. data/lib/active_record/association_relation.rb +35 -0
  9. data/lib/active_record/associations/alias_tracker.rb +47 -36
  10. data/lib/active_record/associations/association.rb +73 -55
  11. data/lib/active_record/associations/association_scope.rb +143 -82
  12. data/lib/active_record/associations/belongs_to_association.rb +65 -25
  13. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +7 -2
  14. data/lib/active_record/associations/builder/association.rb +125 -31
  15. data/lib/active_record/associations/builder/belongs_to.rb +89 -61
  16. data/lib/active_record/associations/builder/collection_association.rb +69 -49
  17. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +113 -42
  18. data/lib/active_record/associations/builder/has_many.rb +8 -64
  19. data/lib/active_record/associations/builder/has_one.rb +12 -51
  20. data/lib/active_record/associations/builder/singular_association.rb +23 -17
  21. data/lib/active_record/associations/collection_association.rb +251 -177
  22. data/lib/active_record/associations/collection_proxy.rb +963 -63
  23. data/lib/active_record/associations/foreign_association.rb +11 -0
  24. data/lib/active_record/associations/has_many_association.rb +113 -22
  25. data/lib/active_record/associations/has_many_through_association.rb +99 -39
  26. data/lib/active_record/associations/has_one_association.rb +43 -20
  27. data/lib/active_record/associations/has_one_through_association.rb +1 -1
  28. data/lib/active_record/associations/join_dependency/join_association.rb +76 -107
  29. data/lib/active_record/associations/join_dependency/join_base.rb +7 -9
  30. data/lib/active_record/associations/join_dependency/join_part.rb +30 -37
  31. data/lib/active_record/associations/join_dependency.rb +230 -156
  32. data/lib/active_record/associations/preloader/association.rb +96 -55
  33. data/lib/active_record/associations/preloader/collection_association.rb +3 -3
  34. data/lib/active_record/associations/preloader/has_many_through.rb +7 -3
  35. data/lib/active_record/associations/preloader/has_one.rb +1 -1
  36. data/lib/active_record/associations/preloader/singular_association.rb +3 -3
  37. data/lib/active_record/associations/preloader/through_association.rb +62 -33
  38. data/lib/active_record/associations/preloader.rb +101 -79
  39. data/lib/active_record/associations/singular_association.rb +29 -13
  40. data/lib/active_record/associations/through_association.rb +30 -16
  41. data/lib/active_record/associations.rb +463 -345
  42. data/lib/active_record/attribute.rb +163 -0
  43. data/lib/active_record/attribute_assignment.rb +142 -151
  44. data/lib/active_record/attribute_decorators.rb +66 -0
  45. data/lib/active_record/attribute_methods/before_type_cast.rb +52 -7
  46. data/lib/active_record/attribute_methods/dirty.rb +137 -57
  47. data/lib/active_record/attribute_methods/primary_key.rb +50 -36
  48. data/lib/active_record/attribute_methods/query.rb +5 -4
  49. data/lib/active_record/attribute_methods/read.rb +73 -106
  50. data/lib/active_record/attribute_methods/serialization.rb +44 -94
  51. data/lib/active_record/attribute_methods/time_zone_conversion.rb +49 -45
  52. data/lib/active_record/attribute_methods/write.rb +57 -44
  53. data/lib/active_record/attribute_methods.rb +301 -141
  54. data/lib/active_record/attribute_set/builder.rb +106 -0
  55. data/lib/active_record/attribute_set.rb +81 -0
  56. data/lib/active_record/attributes.rb +147 -0
  57. data/lib/active_record/autosave_association.rb +246 -217
  58. data/lib/active_record/base.rb +70 -474
  59. data/lib/active_record/callbacks.rb +66 -28
  60. data/lib/active_record/coders/json.rb +13 -0
  61. data/lib/active_record/coders/yaml_column.rb +18 -21
  62. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +396 -219
  63. data/lib/active_record/connection_adapters/abstract/database_limits.rb +9 -0
  64. data/lib/active_record/connection_adapters/abstract/database_statements.rb +167 -164
  65. data/lib/active_record/connection_adapters/abstract/query_cache.rb +29 -24
  66. data/lib/active_record/connection_adapters/abstract/quoting.rb +74 -55
  67. data/lib/active_record/connection_adapters/abstract/savepoints.rb +21 -0
  68. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +125 -0
  69. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +261 -169
  70. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +50 -0
  71. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +707 -259
  72. data/lib/active_record/connection_adapters/abstract/transaction.rb +215 -0
  73. data/lib/active_record/connection_adapters/abstract_adapter.rb +298 -89
  74. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +466 -196
  75. data/lib/active_record/connection_adapters/column.rb +31 -245
  76. data/lib/active_record/connection_adapters/connection_specification.rb +275 -0
  77. data/lib/active_record/connection_adapters/mysql2_adapter.rb +45 -57
  78. data/lib/active_record/connection_adapters/mysql_adapter.rb +180 -123
  79. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +93 -0
  80. data/lib/active_record/connection_adapters/postgresql/column.rb +20 -0
  81. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +232 -0
  82. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +100 -0
  83. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +52 -0
  84. data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +13 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +15 -0
  86. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +46 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +11 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +36 -0
  89. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +13 -0
  90. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +19 -0
  91. data/lib/active_record/connection_adapters/postgresql/oid/float.rb +21 -0
  92. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +59 -0
  93. data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +13 -0
  94. data/lib/active_record/connection_adapters/postgresql/oid/infinity.rb +13 -0
  95. data/lib/active_record/connection_adapters/postgresql/oid/integer.rb +11 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/json.rb +35 -0
  97. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +23 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +43 -0
  99. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +43 -0
  100. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +79 -0
  101. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +19 -0
  102. data/lib/active_record/connection_adapters/postgresql/oid/time.rb +11 -0
  103. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +109 -0
  104. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +21 -0
  105. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +26 -0
  106. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +28 -0
  107. data/lib/active_record/connection_adapters/postgresql/oid.rb +36 -0
  108. data/lib/active_record/connection_adapters/postgresql/quoting.rb +108 -0
  109. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  110. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +152 -0
  111. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +596 -0
  112. data/lib/active_record/connection_adapters/postgresql/utils.rb +77 -0
  113. data/lib/active_record/connection_adapters/postgresql_adapter.rb +430 -999
  114. data/lib/active_record/connection_adapters/schema_cache.rb +52 -27
  115. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +579 -22
  116. data/lib/active_record/connection_handling.rb +132 -0
  117. data/lib/active_record/core.rb +579 -0
  118. data/lib/active_record/counter_cache.rb +157 -105
  119. data/lib/active_record/dynamic_matchers.rb +119 -63
  120. data/lib/active_record/enum.rb +197 -0
  121. data/lib/active_record/errors.rb +94 -36
  122. data/lib/active_record/explain.rb +15 -63
  123. data/lib/active_record/explain_registry.rb +30 -0
  124. data/lib/active_record/explain_subscriber.rb +9 -5
  125. data/lib/active_record/fixture_set/file.rb +56 -0
  126. data/lib/active_record/fixtures.rb +302 -215
  127. data/lib/active_record/gem_version.rb +15 -0
  128. data/lib/active_record/inheritance.rb +143 -70
  129. data/lib/active_record/integration.rb +65 -12
  130. data/lib/active_record/legacy_yaml_adapter.rb +30 -0
  131. data/lib/active_record/locale/en.yml +8 -1
  132. data/lib/active_record/locking/optimistic.rb +73 -52
  133. data/lib/active_record/locking/pessimistic.rb +5 -5
  134. data/lib/active_record/log_subscriber.rb +24 -21
  135. data/lib/active_record/migration/command_recorder.rb +124 -32
  136. data/lib/active_record/migration/join_table.rb +15 -0
  137. data/lib/active_record/migration.rb +511 -213
  138. data/lib/active_record/model_schema.rb +91 -117
  139. data/lib/active_record/nested_attributes.rb +184 -130
  140. data/lib/active_record/no_touching.rb +52 -0
  141. data/lib/active_record/null_relation.rb +81 -0
  142. data/lib/active_record/persistence.rb +276 -117
  143. data/lib/active_record/query_cache.rb +19 -37
  144. data/lib/active_record/querying.rb +28 -18
  145. data/lib/active_record/railtie.rb +73 -40
  146. data/lib/active_record/railties/console_sandbox.rb +3 -4
  147. data/lib/active_record/railties/controller_runtime.rb +4 -3
  148. data/lib/active_record/railties/databases.rake +141 -416
  149. data/lib/active_record/railties/jdbcmysql_error.rb +1 -1
  150. data/lib/active_record/readonly_attributes.rb +1 -4
  151. data/lib/active_record/reflection.rb +513 -154
  152. data/lib/active_record/relation/batches.rb +91 -43
  153. data/lib/active_record/relation/calculations.rb +199 -161
  154. data/lib/active_record/relation/delegation.rb +116 -25
  155. data/lib/active_record/relation/finder_methods.rb +362 -248
  156. data/lib/active_record/relation/merger.rb +193 -0
  157. data/lib/active_record/relation/predicate_builder/array_handler.rb +48 -0
  158. data/lib/active_record/relation/predicate_builder/relation_handler.rb +13 -0
  159. data/lib/active_record/relation/predicate_builder.rb +135 -43
  160. data/lib/active_record/relation/query_methods.rb +928 -167
  161. data/lib/active_record/relation/spawn_methods.rb +48 -149
  162. data/lib/active_record/relation.rb +352 -207
  163. data/lib/active_record/result.rb +101 -10
  164. data/lib/active_record/runtime_registry.rb +22 -0
  165. data/lib/active_record/sanitization.rb +56 -59
  166. data/lib/active_record/schema.rb +19 -13
  167. data/lib/active_record/schema_dumper.rb +106 -63
  168. data/lib/active_record/schema_migration.rb +53 -0
  169. data/lib/active_record/scoping/default.rb +50 -57
  170. data/lib/active_record/scoping/named.rb +73 -109
  171. data/lib/active_record/scoping.rb +58 -123
  172. data/lib/active_record/serialization.rb +6 -2
  173. data/lib/active_record/serializers/xml_serializer.rb +12 -22
  174. data/lib/active_record/statement_cache.rb +111 -0
  175. data/lib/active_record/store.rb +168 -15
  176. data/lib/active_record/tasks/database_tasks.rb +299 -0
  177. data/lib/active_record/tasks/mysql_database_tasks.rb +159 -0
  178. data/lib/active_record/tasks/postgresql_database_tasks.rb +101 -0
  179. data/lib/active_record/tasks/sqlite_database_tasks.rb +55 -0
  180. data/lib/active_record/timestamp.rb +23 -16
  181. data/lib/active_record/transactions.rb +125 -79
  182. data/lib/active_record/type/big_integer.rb +13 -0
  183. data/lib/active_record/type/binary.rb +50 -0
  184. data/lib/active_record/type/boolean.rb +31 -0
  185. data/lib/active_record/type/date.rb +50 -0
  186. data/lib/active_record/type/date_time.rb +54 -0
  187. data/lib/active_record/type/decimal.rb +64 -0
  188. data/lib/active_record/type/decimal_without_scale.rb +11 -0
  189. data/lib/active_record/type/decorator.rb +14 -0
  190. data/lib/active_record/type/float.rb +19 -0
  191. data/lib/active_record/type/hash_lookup_type_map.rb +23 -0
  192. data/lib/active_record/type/integer.rb +59 -0
  193. data/lib/active_record/type/mutable.rb +16 -0
  194. data/lib/active_record/type/numeric.rb +36 -0
  195. data/lib/active_record/type/serialized.rb +62 -0
  196. data/lib/active_record/type/string.rb +40 -0
  197. data/lib/active_record/type/text.rb +11 -0
  198. data/lib/active_record/type/time.rb +26 -0
  199. data/lib/active_record/type/time_value.rb +38 -0
  200. data/lib/active_record/type/type_map.rb +64 -0
  201. data/lib/active_record/type/unsigned_integer.rb +15 -0
  202. data/lib/active_record/type/value.rb +110 -0
  203. data/lib/active_record/type.rb +23 -0
  204. data/lib/active_record/validations/associated.rb +24 -16
  205. data/lib/active_record/validations/presence.rb +67 -0
  206. data/lib/active_record/validations/uniqueness.rb +123 -64
  207. data/lib/active_record/validations.rb +36 -29
  208. data/lib/active_record/version.rb +5 -7
  209. data/lib/active_record.rb +66 -46
  210. data/lib/rails/generators/active_record/migration/migration_generator.rb +53 -8
  211. data/lib/rails/generators/active_record/{model/templates/migration.rb → migration/templates/create_table_migration.rb} +5 -1
  212. data/lib/rails/generators/active_record/migration/templates/migration.rb +20 -15
  213. data/lib/rails/generators/active_record/migration.rb +11 -8
  214. data/lib/rails/generators/active_record/model/model_generator.rb +9 -4
  215. data/lib/rails/generators/active_record/model/templates/model.rb +4 -6
  216. data/lib/rails/generators/active_record/model/templates/module.rb +1 -1
  217. data/lib/rails/generators/active_record.rb +3 -11
  218. metadata +101 -45
  219. data/examples/associations.png +0 -0
  220. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +0 -63
  221. data/lib/active_record/associations/join_helper.rb +0 -55
  222. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +0 -60
  223. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +0 -32
  224. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +0 -191
  225. data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -583
  226. data/lib/active_record/dynamic_finder_match.rb +0 -68
  227. data/lib/active_record/dynamic_scope_match.rb +0 -23
  228. data/lib/active_record/fixtures/file.rb +0 -65
  229. data/lib/active_record/identity_map.rb +0 -162
  230. data/lib/active_record/observer.rb +0 -121
  231. data/lib/active_record/session_store.rb +0 -360
  232. data/lib/active_record/test_case.rb +0 -73
  233. data/lib/rails/generators/active_record/observer/observer_generator.rb +0 -15
  234. data/lib/rails/generators/active_record/observer/templates/observer.rb +0 -4
  235. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +0 -25
  236. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +0 -12
@@ -1,34 +1,27 @@
1
- begin
2
- require 'psych'
3
- rescue LoadError
4
- end
5
-
6
1
  require 'yaml'
7
2
  require 'set'
8
- require 'thread'
9
3
  require 'active_support/benchmarkable'
10
4
  require 'active_support/dependencies'
11
5
  require 'active_support/descendants_tracker'
12
6
  require 'active_support/time'
13
- require 'active_support/core_ext/class/attribute'
14
- require 'active_support/core_ext/class/attribute_accessors'
7
+ require 'active_support/core_ext/module/attribute_accessors'
15
8
  require 'active_support/core_ext/class/delegating_attributes'
16
- require 'active_support/core_ext/class/attribute'
17
9
  require 'active_support/core_ext/array/extract_options'
18
10
  require 'active_support/core_ext/hash/deep_merge'
19
- require 'active_support/core_ext/hash/indifferent_access'
20
11
  require 'active_support/core_ext/hash/slice'
12
+ require 'active_support/core_ext/hash/transform_values'
21
13
  require 'active_support/core_ext/string/behavior'
22
14
  require 'active_support/core_ext/kernel/singleton_class'
23
- require 'active_support/core_ext/module/delegation'
24
15
  require 'active_support/core_ext/module/introspection'
25
16
  require 'active_support/core_ext/object/duplicable'
26
- require 'active_support/core_ext/object/blank'
27
- require 'active_support/deprecation'
17
+ require 'active_support/core_ext/class/subclasses'
28
18
  require 'arel'
19
+ require 'active_record/attribute_decorators'
29
20
  require 'active_record/errors'
30
21
  require 'active_record/log_subscriber'
31
22
  require 'active_record/explain_subscriber'
23
+ require 'active_record/relation/delegation'
24
+ require 'active_record/attributes'
32
25
 
33
26
  module ActiveRecord #:nodoc:
34
27
  # = Active Record
@@ -47,7 +40,7 @@ module ActiveRecord #:nodoc:
47
40
  # method is especially useful when you're receiving the data from somewhere else, like an
48
41
  # HTTP request. It works like this:
49
42
  #
50
- # user = User.new(:name => "David", :occupation => "Code Artist")
43
+ # user = User.new(name: "David", occupation: "Code Artist")
51
44
  # user.name # => "David"
52
45
  #
53
46
  # You can also use block initialization:
@@ -80,7 +73,7 @@ module ActiveRecord #:nodoc:
80
73
  # end
81
74
  #
82
75
  # def self.authenticate_safely_simply(user_name, password)
83
- # where(:user_name => user_name, :password => password).first
76
+ # where(user_name: user_name, password: password).first
84
77
  # end
85
78
  # end
86
79
  #
@@ -98,27 +91,27 @@ module ActiveRecord #:nodoc:
98
91
  #
99
92
  # Company.where(
100
93
  # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
101
- # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
94
+ # { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
102
95
  # ).first
103
96
  #
104
97
  # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
105
98
  # operator. For instance:
106
99
  #
107
- # Student.where(:first_name => "Harvey", :status => 1)
100
+ # Student.where(first_name: "Harvey", status: 1)
108
101
  # Student.where(params[:student])
109
102
  #
110
103
  # A range may be used in the hash to use the SQL BETWEEN operator:
111
104
  #
112
- # Student.where(:grade => 9..12)
105
+ # Student.where(grade: 9..12)
113
106
  #
114
107
  # An array may be used in the hash to use the SQL IN operator:
115
108
  #
116
- # Student.where(:grade => [9,11,12])
109
+ # Student.where(grade: [9,11,12])
117
110
  #
118
111
  # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
119
112
  # can be used to qualify the table name of a particular condition. For instance:
120
113
  #
121
- # Student.joins(:schools).where(:schools => { :category => 'public' })
114
+ # Student.joins(:schools).where(schools: { category: 'public' })
122
115
  # Student.joins(:schools).where('schools.category' => 'public' )
123
116
  #
124
117
  # == Overwriting default accessors
@@ -126,36 +119,36 @@ module ActiveRecord #:nodoc:
126
119
  # All column values are automatically available through basic accessors on the Active Record
127
120
  # object, but sometimes you want to specialize this behavior. This can be done by overwriting
128
121
  # the default accessors (using the same name as the attribute) and calling
129
- # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
130
- # change things.
122
+ # +super+ to actually change things.
131
123
  #
132
124
  # class Song < ActiveRecord::Base
133
125
  # # Uses an integer of seconds to hold the length of the song
134
126
  #
135
127
  # def length=(minutes)
136
- # write_attribute(:length, minutes.to_i * 60)
128
+ # super(minutes.to_i * 60)
137
129
  # end
138
130
  #
139
131
  # def length
140
- # read_attribute(:length) / 60
132
+ # super / 60
141
133
  # end
142
134
  # end
143
135
  #
144
136
  # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
145
- # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
137
+ # or <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
146
138
  #
147
139
  # == Attribute query methods
148
140
  #
149
141
  # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
150
142
  # Query methods allow you to test whether an attribute value is present.
143
+ # For numeric values, present is defined as non-zero.
151
144
  #
152
145
  # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
153
146
  # to determine whether the user has a name:
154
147
  #
155
- # user = User.new(:name => "David")
148
+ # user = User.new(name: "David")
156
149
  # user.name? # => true
157
150
  #
158
- # anonymous = User.new(:name => "")
151
+ # anonymous = User.new(name: "")
159
152
  # anonymous.name? # => false
160
153
  #
161
154
  # == Accessing attributes before they have been typecasted
@@ -171,14 +164,11 @@ module ActiveRecord #:nodoc:
171
164
  #
172
165
  # == Dynamic attribute-based finders
173
166
  #
174
- # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects
167
+ # Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
175
168
  # by simple queries without turning to SQL. They work by appending the name of an attribute
176
- # to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
177
- # like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
178
- # <tt>Payment.find_by_transaction_id</tt>. Instead of writing
179
- # <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
180
- # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
181
- # <tt>Person.find_all_by_last_name(last_name)</tt>.
169
+ # to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
170
+ # Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
171
+ # <tt>Person.find_by_user_name(user_name)</tt>.
182
172
  #
183
173
  # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
184
174
  # <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
@@ -186,51 +176,12 @@ module ActiveRecord #:nodoc:
186
176
  #
187
177
  # It's also possible to use multiple attributes in the same find by separating them with "_and_".
188
178
  #
189
- # Person.where(:user_name => user_name, :password => password).first
179
+ # Person.find_by(user_name: user_name, password: password)
190
180
  # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
191
181
  #
192
182
  # It's even possible to call these dynamic finder methods on relations and named scopes.
193
183
  #
194
- # Payment.order("created_on").find_all_by_amount(50)
195
- # Payment.pending.find_last_by_amount(100)
196
- #
197
- # The same dynamic finder style can be used to create the object if it doesn't already exist.
198
- # This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
199
- # it already exists and otherwise creates it, then returns it. Protected attributes won't be set
200
- # unless they are given in a block.
201
- #
202
- # # No 'Summer' tag exists
203
- # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
204
- #
205
- # # Now the 'Summer' tag does exist
206
- # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
207
- #
208
- # # Now 'Bob' exist and is an 'admin'
209
- # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
210
- #
211
- # Adding an exclamation point (!) on to the end of <tt>find_or_create_by_</tt> will
212
- # raise an <tt>ActiveRecord::RecordInvalid</tt> error if the new record is invalid.
213
- #
214
- # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
215
- # saving it first. Protected attributes won't be set unless they are given in a block.
216
- #
217
- # # No 'Winter' tag exists
218
- # winter = Tag.find_or_initialize_by_name("Winter")
219
- # winter.persisted? # false
220
- #
221
- # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
222
- # a list of parameters.
223
- #
224
- # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
225
- #
226
- # That will either find an existing tag named "rails", or create a new one while setting the
227
- # user that created it.
228
- #
229
- # Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
230
- # using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
231
- # but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
232
- #
233
- # User.scoped_by_user_name('David')
184
+ # Payment.order("created_on").find_by_amount(50)
234
185
  #
235
186
  # == Saving arrays, hashes, and other non-mappable objects in text columns
236
187
  #
@@ -243,7 +194,7 @@ module ActiveRecord #:nodoc:
243
194
  # serialize :preferences
244
195
  # end
245
196
  #
246
- # user = User.create(:preferences => { "background" => "black", "display" => large })
197
+ # user = User.create(preferences: { "background" => "black", "display" => large })
247
198
  # User.find(user.id).preferences # => { "background" => "black", "display" => large }
248
199
  #
249
200
  # You can also specify a class option as the second parameter that'll raise an exception
@@ -253,7 +204,7 @@ module ActiveRecord #:nodoc:
253
204
  # serialize :preferences, Hash
254
205
  # end
255
206
  #
256
- # user = User.create(:preferences => %w( one two three ))
207
+ # user = User.create(preferences: %w( one two three ))
257
208
  # User.find(user.id).preferences # raises SerializationTypeMismatch
258
209
  #
259
210
  # When you specify a class option, the default value for that attribute will be a new
@@ -269,25 +220,9 @@ module ActiveRecord #:nodoc:
269
220
  #
270
221
  # == Single table inheritance
271
222
  #
272
- # Active Record allows inheritance by storing the name of the class in a column that by
273
- # default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
274
- # This means that an inheritance looking like this:
275
- #
276
- # class Company < ActiveRecord::Base; end
277
- # class Firm < Company; end
278
- # class Client < Company; end
279
- # class PriorityClient < Client; end
280
- #
281
- # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
282
- # the companies table with type = "Firm". You can then fetch this row again using
283
- # <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
284
- #
285
- # If you don't have a type column defined in your table, single-table inheritance won't
286
- # be triggered. In that case, it'll work just like normal subclasses with no special magic
287
- # for differentiating between them or reloading the right type with find.
288
- #
289
- # Note, all the attributes for all the cases are kept in the same table. Read more:
290
- # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
223
+ # Active Record allows inheritance by storing the name of the class in a
224
+ # column that is named "type" by default. See ActiveRecord::Inheritance for
225
+ # more details.
291
226
  #
292
227
  # == Connection to multiple databases in different models
293
228
  #
@@ -311,410 +246,71 @@ module ActiveRecord #:nodoc:
311
246
  # (or a bad spelling of an existing one).
312
247
  # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
313
248
  # specified in the association definition.
314
- # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
315
- # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt>
249
+ # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
250
+ # <tt>attributes=</tt> method.
251
+ # You can inspect the +attribute+ property of the exception object to determine which attribute
252
+ # triggered the error.
253
+ # * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
316
254
  # before querying.
317
- # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
318
- # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
319
- # nothing was found, please check its documentation for further details.
320
- # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
321
255
  # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
322
256
  # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
323
257
  # AttributeAssignmentError
324
258
  # objects that should be inspected to determine which attributes triggered the errors.
325
- # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
326
- # <tt>attributes=</tt> method.
327
- # You can inspect the +attribute+ property of the exception object to determine which attribute
328
- # triggered the error.
259
+ # * RecordInvalid - raised by save! and create! when the record is invalid.
260
+ # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
261
+ # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
262
+ # nothing was found, please check its documentation for further details.
263
+ # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
264
+ # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
329
265
  #
330
266
  # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
331
267
  # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
332
268
  # instances in the current object space.
333
269
  class Base
334
- ##
335
- # :singleton-method:
336
- # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
337
- # which is then passed on to any new database connections made and which can be retrieved on both
338
- # a class and instance level by calling +logger+.
339
- cattr_accessor :logger, :instance_writer => false
340
-
341
- ##
342
- # :singleton-method:
343
- # Contains the database configuration - as is typically stored in config/database.yml -
344
- # as a Hash.
345
- #
346
- # For example, the following database.yml...
347
- #
348
- # development:
349
- # adapter: sqlite3
350
- # database: db/development.sqlite3
351
- #
352
- # production:
353
- # adapter: sqlite3
354
- # database: db/production.sqlite3
355
- #
356
- # ...would result in ActiveRecord::Base.configurations to look like this:
357
- #
358
- # {
359
- # 'development' => {
360
- # 'adapter' => 'sqlite3',
361
- # 'database' => 'db/development.sqlite3'
362
- # },
363
- # 'production' => {
364
- # 'adapter' => 'sqlite3',
365
- # 'database' => 'db/production.sqlite3'
366
- # }
367
- # }
368
- cattr_accessor :configurations, :instance_writer => false
369
- @@configurations = {}
370
-
371
- ##
372
- # :singleton-method:
373
- # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling
374
- # dates and times from the database. This is set to :local by default.
375
- cattr_accessor :default_timezone, :instance_writer => false
376
- @@default_timezone = :local
377
-
378
- ##
379
- # :singleton-method:
380
- # Specifies the format to use when dumping the database schema with Rails'
381
- # Rakefile. If :sql, the schema is dumped as (potentially database-
382
- # specific) SQL statements. If :ruby, the schema is dumped as an
383
- # ActiveRecord::Schema file which can be loaded into any database that
384
- # supports migrations. Use :ruby if you want to have different database
385
- # adapters for, e.g., your development and test environments.
386
- cattr_accessor :schema_format , :instance_writer => false
387
- @@schema_format = :ruby
388
-
389
- ##
390
- # :singleton-method:
391
- # Specify whether or not to use timestamps for migration versions
392
- cattr_accessor :timestamped_migrations , :instance_writer => false
393
- @@timestamped_migrations = true
394
-
395
- class << self # Class methods
396
- def inherited(child_class) #:nodoc:
397
- child_class.initialize_generated_modules
398
- super
399
- end
400
-
401
- def initialize_generated_modules #:nodoc:
402
- @attribute_methods_mutex = Mutex.new
403
-
404
- # force attribute methods to be higher in inheritance hierarchy than other generated methods
405
- generated_attribute_methods
406
- generated_feature_methods
407
- end
408
-
409
- def generated_feature_methods
410
- @generated_feature_methods ||= begin
411
- mod = const_set(:GeneratedFeatureMethods, Module.new)
412
- include mod
413
- mod
414
- end
415
- end
416
-
417
- # Returns a string like 'Post(id:integer, title:string, body:text)'
418
- def inspect
419
- if self == Base
420
- super
421
- elsif abstract_class?
422
- "#{super}(abstract)"
423
- elsif table_exists?
424
- attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
425
- "#{super}(#{attr_list})"
426
- else
427
- "#{super}(Table doesn't exist)"
428
- end
429
- end
430
-
431
- # Overwrite the default class equality method to provide support for association proxies.
432
- def ===(object)
433
- object.is_a?(self)
434
- end
435
-
436
- def arel_table
437
- @arel_table ||= Arel::Table.new(table_name, arel_engine)
438
- end
439
-
440
- def arel_engine
441
- @arel_engine ||= begin
442
- if self == ActiveRecord::Base
443
- ActiveRecord::Base
444
- else
445
- connection_handler.retrieve_connection_pool(self) ? self : superclass.arel_engine
446
- end
447
- end
448
- end
449
-
450
- private
451
-
452
- def relation #:nodoc:
453
- relation = Relation.new(self, arel_table)
454
-
455
- if finder_needs_type_condition?
456
- relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
457
- else
458
- relation
459
- end
460
- end
461
- end
462
-
463
- public
464
- # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
465
- # attributes but not yet saved (pass a hash with key names matching the associated table column names).
466
- # In both instances, valid attribute keys are determined by the column names of the associated table --
467
- # hence you can't have attributes that aren't part of the table columns.
468
- #
469
- # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
470
- # in the +options+ parameter.
471
- #
472
- # ==== Examples
473
- # # Instantiates a single new object
474
- # User.new(:first_name => 'Jamie')
475
- #
476
- # # Instantiates a single new object using the :admin mass-assignment security role
477
- # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
478
- #
479
- # # Instantiates a single new object bypassing mass-assignment security
480
- # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
481
- def initialize(attributes = nil, options = {})
482
- defaults = Hash[self.class.column_defaults.map { |k, v| [k, v.duplicable? ? v.dup : v] }]
483
- @attributes = self.class.initialize_attributes(defaults)
484
- @association_cache = {}
485
- @aggregation_cache = {}
486
- @attributes_cache = {}
487
- @new_record = true
488
- @readonly = false
489
- @destroyed = false
490
- @marked_for_destruction = false
491
- @previously_changed = {}
492
- @changed_attributes = {}
493
-
494
- ensure_proper_type
495
-
496
- populate_with_current_scope_attributes
497
-
498
- assign_attributes(attributes, options) if attributes
499
-
500
- yield self if block_given?
501
- run_callbacks :initialize
502
- end
503
-
504
- # Initialize an empty model object from +coder+. +coder+ must contain
505
- # the attributes necessary for initializing an empty model object. For
506
- # example:
507
- #
508
- # class Post < ActiveRecord::Base
509
- # end
510
- #
511
- # post = Post.allocate
512
- # post.init_with('attributes' => { 'title' => 'hello world' })
513
- # post.title # => 'hello world'
514
- def init_with(coder)
515
- @attributes = self.class.initialize_attributes(coder['attributes'])
516
- @relation = nil
517
-
518
- @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
519
- @association_cache = {}
520
- @aggregation_cache = {}
521
- @readonly = @destroyed = @marked_for_destruction = false
522
- @new_record = false
523
- run_callbacks :find
524
- run_callbacks :initialize
525
-
526
- self
527
- end
528
-
529
- # Duped objects have no id assigned and are treated as new records. Note
530
- # that this is a "shallow" copy as it copies the object's attributes
531
- # only, not its associations. The extent of a "deep" copy is application
532
- # specific and is therefore left to the application to implement according
533
- # to its need.
534
- # The dup method does not preserve the timestamps (created|updated)_(at|on).
535
- def initialize_dup(other)
536
- cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
537
- self.class.initialize_attributes(cloned_attributes, :serialized => false)
538
-
539
- cloned_attributes.delete(self.class.primary_key)
540
-
541
- @attributes = cloned_attributes
542
-
543
- _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks)
544
-
545
- @changed_attributes = {}
546
- self.class.column_defaults.each do |attr, orig_value|
547
- @changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
548
- end
549
-
550
- @aggregation_cache = {}
551
- @association_cache = {}
552
- @attributes_cache = {}
553
- @new_record = true
554
-
555
- ensure_proper_type
556
- super
557
- end
558
-
559
- # Backport dup from 1.9 so that initialize_dup() gets called
560
- unless Object.respond_to?(:initialize_dup, true)
561
- def dup # :nodoc:
562
- copy = super
563
- copy.initialize_dup(self)
564
- copy
565
- end
566
- end
567
-
568
- # Populate +coder+ with attributes about this record that should be
569
- # serialized. The structure of +coder+ defined in this method is
570
- # guaranteed to match the structure of +coder+ passed to the +init_with+
571
- # method.
572
- #
573
- # Example:
574
- #
575
- # class Post < ActiveRecord::Base
576
- # end
577
- # coder = {}
578
- # Post.new.encode_with(coder)
579
- # coder # => { 'id' => nil, ... }
580
- def encode_with(coder)
581
- coder['attributes'] = attributes
582
- end
583
-
584
- # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
585
- # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
586
- #
587
- # Note that new records are different from any other record by definition, unless the
588
- # other record is the receiver itself. Besides, if you fetch existing records with
589
- # +select+ and leave the ID out, you're on your own, this predicate will return false.
590
- #
591
- # Note also that destroying a record preserves its ID in the model instance, so deleted
592
- # models are still comparable.
593
- def ==(comparison_object)
594
- super ||
595
- comparison_object.instance_of?(self.class) &&
596
- id.present? &&
597
- comparison_object.id == id
598
- end
599
- alias :eql? :==
600
-
601
- # Delegates to id in order to allow two records of the same type and id to work with something like:
602
- # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
603
- def hash
604
- id.hash
605
- end
606
-
607
- # Freeze the attributes hash such that associations are still accessible, even on destroyed records.
608
- def freeze
609
- @attributes.freeze; self
610
- end
611
-
612
- # Returns +true+ if the attributes hash has been frozen.
613
- def frozen?
614
- @attributes.frozen?
615
- end
616
-
617
- # Allows sort on objects
618
- def <=>(other_object)
619
- if other_object.is_a?(self.class)
620
- self.to_key <=> other_object.to_key
621
- else
622
- nil
623
- end
624
- end
625
-
626
- # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
627
- # attributes will be marked as read only since they cannot be saved.
628
- def readonly?
629
- @readonly
630
- end
631
-
632
- # Marks this record as read only.
633
- def readonly!
634
- @readonly = true
635
- end
636
-
637
- # Returns the contents of the record as a nicely formatted string.
638
- def inspect
639
- inspection = if @attributes
640
- self.class.column_names.collect { |name|
641
- if has_attribute?(name)
642
- "#{name}: #{attribute_for_inspect(name)}"
643
- end
644
- }.compact.join(", ")
645
- else
646
- "not initialized"
647
- end
648
- "#<#{self.class} #{inspection}>"
649
- end
650
-
651
- # Hackery to accomodate Syck. Remove for 4.0.
652
- def to_yaml(opts = {}) #:nodoc:
653
- if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
654
- super
655
- else
656
- coder = {}
657
- encode_with(coder)
658
- YAML.quick_emit(self, opts) do |out|
659
- out.map(taguri, to_yaml_style) do |map|
660
- coder.each { |k, v| map.add(k, v) }
661
- end
662
- end
663
- end
664
- end
665
-
666
- # Hackery to accomodate Syck. Remove for 4.0.
667
- def yaml_initialize(tag, coder) #:nodoc:
668
- init_with(coder)
669
- end
670
-
671
- private
672
-
673
- # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
674
- # of the array, and then rescues from the possible NoMethodError. If those elements are
675
- # ActiveRecord::Base's, then this triggers the various method_missing's that we have,
676
- # which significantly impacts upon performance.
677
- #
678
- # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
679
- #
680
- # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/
681
- def to_ary # :nodoc:
682
- nil
683
- end
684
-
685
- include ActiveRecord::Persistence
686
270
  extend ActiveModel::Naming
687
- extend QueryCache::ClassMethods
271
+
688
272
  extend ActiveSupport::Benchmarkable
689
273
  extend ActiveSupport::DescendantsTracker
690
274
 
275
+ extend ConnectionHandling
276
+ extend QueryCache::ClassMethods
691
277
  extend Querying
278
+ extend Translation
279
+ extend DynamicMatchers
280
+ extend Explain
281
+ extend Enum
282
+ extend Delegation::DelegateCache
283
+
284
+ include Core
285
+ include Persistence
692
286
  include ReadonlyAttributes
693
287
  include ModelSchema
694
- extend Translation
695
288
  include Inheritance
696
289
  include Scoping
697
- extend DynamicMatchers
698
290
  include Sanitization
699
291
  include AttributeAssignment
700
292
  include ActiveModel::Conversion
701
293
  include Integration
702
294
  include Validations
703
- extend CounterCache
704
- include Locking::Optimistic, Locking::Pessimistic
295
+ include CounterCache
296
+ include Attributes
297
+ include AttributeDecorators
298
+ include Locking::Optimistic
299
+ include Locking::Pessimistic
705
300
  include AttributeMethods
706
- include Callbacks, ActiveModel::Observing, Timestamp
301
+ include Callbacks
302
+ include Timestamp
707
303
  include Associations
708
- include IdentityMap
709
304
  include ActiveModel::SecurePassword
710
- extend Explain
711
-
712
- # AutosaveAssociation needs to be included before Transactions, because we want
713
- # #save_with_autosave_associations to be wrapped inside a transaction.
714
- include AutosaveAssociation, NestedAttributes
715
- include Aggregations, Transactions, Reflection, Serialization, Store
305
+ include AutosaveAssociation
306
+ include NestedAttributes
307
+ include Aggregations
308
+ include Transactions
309
+ include NoTouching
310
+ include Reflection
311
+ include Serialization
312
+ include Store
716
313
  end
717
- end
718
314
 
719
- require 'active_record/connection_adapters/abstract/connection_specification'
720
- ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
315
+ ActiveSupport.run_load_hooks(:active_record, Base)
316
+ end