Skip to content
This repository
Browse code

Update the docs to reflect the new association API

  • Loading branch information...
commit 6fe119650c4e18b68b85edea3761837bc6a8c921 1 parent 9895f6c
Jon Leighton authored August 03, 2012
270  activerecord/lib/active_record/associations.rb
@@ -195,26 +195,6 @@ def association_instance_set(name, association)
195 195
     # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
196 196
     #   <tt>Project#categories.delete(category1)</tt>
197 197
     #
198  
-    # === Overriding generated methods
199  
-    #
200  
-    # Association methods are generated in a module that is included into the model class,
201  
-    # which allows you to easily override with your own methods and call the original
202  
-    # generated method with +super+. For example:
203  
-    #
204  
-    #   class Car < ActiveRecord::Base
205  
-    #     belongs_to :owner
206  
-    #     belongs_to :old_owner
207  
-    #     def owner=(new_owner)
208  
-    #       self.old_owner = self.owner
209  
-    #       super
210  
-    #     end
211  
-    #   end
212  
-    #
213  
-    # If your model class is <tt>Project</tt>, the module is
214  
-    # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
215  
-    # included in the model class immediately after the (anonymous) generated attributes methods
216  
-    # module, meaning an association will override the methods for an attribute with the same name.
217  
-    #
218 198
     # === A word of warning
219 199
     #
220 200
     # Don't create associations that have the same name as instance methods of
@@ -262,6 +242,26 @@ def association_instance_set(name, association)
262 242
     #   others.uniq                       |   X   |    X     |    X
263 243
     #   others.reset                      |   X   |    X     |    X
264 244
     #
  245
+    # === Overriding generated methods
  246
+    #
  247
+    # Association methods are generated in a module that is included into the model class,
  248
+    # which allows you to easily override with your own methods and call the original
  249
+    # generated method with +super+. For example:
  250
+    #
  251
+    #   class Car < ActiveRecord::Base
  252
+    #     belongs_to :owner
  253
+    #     belongs_to :old_owner
  254
+    #     def owner=(new_owner)
  255
+    #       self.old_owner = self.owner
  256
+    #       super
  257
+    #     end
  258
+    #   end
  259
+    #
  260
+    # If your model class is <tt>Project</tt>, the module is
  261
+    # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
  262
+    # included in the model class immediately after the (anonymous) generated attributes methods
  263
+    # module, meaning an association will override the methods for an attribute with the same name.
  264
+    #
265 265
     # == Cardinality and associations
266 266
     #
267 267
     # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
@@ -397,7 +397,28 @@ def association_instance_set(name, association)
397 397
     # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
398 398
     #   saved when the parent is saved.
399 399
     #
400  
-    # === Association callbacks
  400
+    # == Customizing the query
  401
+    #
  402
+    # Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
  403
+    # to customize them. For example, to add a condition:
  404
+    #
  405
+    #   class Blog < ActiveRecord::Base
  406
+    #     has_many :published_posts, -> { where published: true }, class_name: 'Post'
  407
+    #   end
  408
+    #
  409
+    # Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
  410
+    #
  411
+    # === Accessing the owner object
  412
+    #
  413
+    # Sometimes it is useful to have access to the owner object when building the query. The owner
  414
+    # is passed as a parameter to the block. For example, the following association would find all
  415
+    # events that occur on the user's birthday:
  416
+    #
  417
+    #   class User < ActiveRecord::Base
  418
+    #     has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
  419
+    #   end
  420
+    #
  421
+    # == Association callbacks
401 422
     #
402 423
     # Similar to the normal callbacks that hook into the life cycle of an Active Record object,
403 424
     # you can also define callbacks that get triggered when you add an object to or remove an
@@ -424,7 +445,7 @@ def association_instance_set(name, association)
424 445
     # added to the collection. Same with the +before_remove+ callbacks; if an exception is
425 446
     # thrown the object doesn't get removed.
426 447
     #
427  
-    # === Association extensions
  448
+    # == Association extensions
428 449
     #
429 450
     # The proxy objects that control the access to associations can be extended through anonymous
430 451
     # modules. This is especially beneficial for adding new finders, creators, and other
@@ -454,20 +475,11 @@ def association_instance_set(name, association)
454 475
     #   end
455 476
     #
456 477
     #   class Account < ActiveRecord::Base
457  
-    #     has_many :people, :extend => FindOrCreateByNameExtension
  478
+    #     has_many :people, -> { extending FindOrCreateByNameExtension }
458 479
     #   end
459 480
     #
460 481
     #   class Company < ActiveRecord::Base
461  
-    #     has_many :people, :extend => FindOrCreateByNameExtension
462  
-    #   end
463  
-    #
464  
-    # If you need to use multiple named extension modules, you can specify an array of modules
465  
-    # with the <tt>:extend</tt> option.
466  
-    # In the case of name conflicts between methods in the modules, methods in modules later
467  
-    # in the array supercede those earlier in the array.
468  
-    #
469  
-    #   class Account < ActiveRecord::Base
470  
-    #     has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
  482
+    #     has_many :people, -> { extending FindOrCreateByNameExtension }
471 483
     #   end
472 484
     #
473 485
     # Some extensions can only be made to work with knowledge of the association's internals.
@@ -485,7 +497,7 @@ def association_instance_set(name, association)
485 497
     # the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
486 498
     # association extensions.
487 499
     #
488  
-    # === Association Join Models
  500
+    # == Association Join Models
489 501
     #
490 502
     # Has Many associations can be configured with the <tt>:through</tt> option to use an
491 503
     # explicit join model to retrieve the data. This operates similarly to a
@@ -569,7 +581,7 @@ def association_instance_set(name, association)
569 581
     #     belongs_to :tag, :inverse_of => :taggings
570 582
     #   end
571 583
     #
572  
-    # === Nested Associations
  584
+    # == Nested Associations
573 585
     #
574 586
     # You can actually specify *any* association with the <tt>:through</tt> option, including an
575 587
     # association which has a <tt>:through</tt> option itself. For example:
@@ -612,7 +624,7 @@ def association_instance_set(name, association)
612 624
     # add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
613 625
     # intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
614 626
     #
615  
-    # === Polymorphic Associations
  627
+    # == Polymorphic Associations
616 628
     #
617 629
     # Polymorphic associations on models are not restricted on what types of models they
618 630
     # can be associated with. Rather, they specify an interface that a +has_many+ association
@@ -742,7 +754,7 @@ def association_instance_set(name, association)
742 754
     # to include an association which has conditions defined on it:
743 755
     #
744 756
     #   class Post < ActiveRecord::Base
745  
-    #     has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]
  757
+    #     has_many :approved_comments, -> { where approved: true }, :class_name => 'Comment'
746 758
     #   end
747 759
     #
748 760
     #   Post.includes(:approved_comments)
@@ -754,14 +766,11 @@ def association_instance_set(name, association)
754 766
     # returning all the associated objects:
755 767
     #
756 768
     #   class Picture < ActiveRecord::Base
757  
-    #     has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
  769
+    #     has_many :most_recent_comments, -> { order('id DESC').limit(10) }, :class_name => 'Comment'
758 770
     #   end
759 771
     #
760 772
     #   Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
761 773
     #
762  
-    # When eager loaded, conditions are interpolated in the context of the model class, not
763  
-    # the model instance. Conditions are lazily interpolated before the actual model exists.
764  
-    #
765 774
     # Eager loading is supported with polymorphic associations.
766 775
     #
767 776
     #   class Address < ActiveRecord::Base
@@ -839,8 +848,8 @@ def association_instance_set(name, association)
839 848
     #   module MyApplication
840 849
     #     module Business
841 850
     #       class Firm < ActiveRecord::Base
842  
-    #          has_many :clients
843  
-    #        end
  851
+    #         has_many :clients
  852
+    #       end
844 853
     #
845 854
     #       class Client < ActiveRecord::Base; end
846 855
     #     end
@@ -1078,15 +1087,6 @@ module ClassMethods
1078 1087
       #   from the association name. So <tt>has_many :products</tt> will by default be linked
1079 1088
       #   to the Product class, but if the real class name is SpecialProduct, you'll have to
1080 1089
       #   specify it with this option.
1081  
-      # [:conditions]
1082  
-      #   Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
1083  
-      #   SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from
1084  
-      #   the association are scoped if a hash is used.
1085  
-      #   <tt>has_many :posts, :conditions => {:published => true}</tt> will create published
1086  
-      #   posts with <tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.
1087  
-      # [:order]
1088  
-      #   Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
1089  
-      #   such as <tt>last_name, first_name DESC</tt>.
1090 1090
       # [:foreign_key]
1091 1091
       #   Specify the foreign key used for the association. By default this is guessed to be the name
1092 1092
       #   of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
@@ -1104,34 +1104,6 @@ module ClassMethods
1104 1104
       #   If using with the <tt>:through</tt> option, the association on the join model must be
1105 1105
       #   a +belongs_to+, and the records which get deleted are the join records, rather than
1106 1106
       #   the associated records.
1107  
-      #
1108  
-      # [:finder_sql]
1109  
-      #   Specify a complete SQL statement to fetch the association. This is a good way to go for complex
1110  
-      #   associations that depend on multiple tables. May be supplied as a string or a proc where interpolation is
1111  
-      #   required. Note: When this option is used, +find_in_collection+
1112  
-      #   is _not_ added.
1113  
-      # [:counter_sql]
1114  
-      #   Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
1115  
-      #   specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
1116  
-      #   replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
1117  
-      # [:extend]
1118  
-      #   Specify a named module for extending the proxy. See "Association extensions".
1119  
-      # [:include]
1120  
-      #   Specify second-order associations that should be eager loaded when the collection is loaded.
1121  
-      # [:group]
1122  
-      #   An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
1123  
-      # [:having]
1124  
-      #   Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt>
1125  
-      #   returns. Uses the <tt>HAVING</tt> SQL-clause.
1126  
-      # [:limit]
1127  
-      #   An integer determining the limit on the number of rows that should be returned.
1128  
-      # [:offset]
1129  
-      #   An integer determining the offset from where the rows should be fetched. So at 5,
1130  
-      #   it would skip the first 4 rows.
1131  
-      # [:select]
1132  
-      #   By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
1133  
-      #   you want to do a join but not include the joined columns, for example. Do not forget
1134  
-      #   to include the primary and foreign keys, otherwise it will raise an error.
1135 1107
       # [:as]
1136 1108
       #   Specifies a polymorphic interface (See <tt>belongs_to</tt>).
1137 1109
       # [:through]
@@ -1158,10 +1130,6 @@ module ClassMethods
1158 1130
       # [:source_type]
1159 1131
       #   Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
1160 1132
       #   association is a polymorphic +belongs_to+.
1161  
-      # [:uniq]
1162  
-      #   If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
1163  
-      # [:readonly]
1164  
-      #   If true, all the associated objects are readonly through the association.
1165 1133
       # [:validate]
1166 1134
       #   If +false+, don't validate the associated objects when saving the parent object. true by default.
1167 1135
       # [:autosave]
@@ -1177,22 +1145,14 @@ module ClassMethods
1177 1145
       #   See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1178 1146
       #
1179 1147
       # Option examples:
1180  
-      #   has_many :comments, :order => "posted_on"
1181  
-      #   has_many :comments, :include => :author
1182  
-      #   has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
1183  
-      #   has_many :tracks, :order => "position", :dependent => :destroy
1184  
-      #   has_many :comments, :dependent => :nullify
1185  
-      #   has_many :tags, :as => :taggable
1186  
-      #   has_many :reports, :readonly => true
1187  
-      #   has_many :subscribers, :through => :subscriptions, :source => :user
1188  
-      #   has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new {
1189  
-      #       %Q{
1190  
-      #         SELECT DISTINCT *
1191  
-      #         FROM people p, post_subscriptions ps
1192  
-      #         WHERE ps.post_id = #{id} AND ps.person_id = p.id
1193  
-      #         ORDER BY p.first_name
1194  
-      #       }
1195  
-      #   }
  1148
+      #   has_many :comments, -> { order "posted_on" }
  1149
+      #   has_many :comments, -> { includes :author }
  1150
+      #   has_many :people, -> { where("deleted = 0").order("name") }, class_name: "Person"
  1151
+      #   has_many :tracks, -> { order "position" }, dependent: :destroy
  1152
+      #   has_many :comments, dependent: :nullify
  1153
+      #   has_many :tags, as: :taggable
  1154
+      #   has_many :reports, -> { readonly }
  1155
+      #   has_many :subscribers, through: :subscriptions, source: :user
1196 1156
       def has_many(name, scope = nil, options = {}, &extension)
1197 1157
         Builder::HasMany.build(self, name, scope, options, &extension)
1198 1158
       end
@@ -1242,14 +1202,6 @@ def has_many(name, scope = nil, options = {}, &extension)
1242 1202
       #   Specify the class name of the association. Use it only if that name can't be inferred
1243 1203
       #   from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
1244 1204
       #   if the real class name is Person, you'll have to specify it with this option.
1245  
-      # [:conditions]
1246  
-      #   Specify the conditions that the associated object must meet in order to be included as a +WHERE+
1247  
-      #   SQL fragment, such as <tt>rank = 5</tt>. Record creation from the association is scoped if a hash
1248  
-      #   is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create
1249  
-      #   an enabled account with <tt>@company.create_account</tt> or <tt>@company.build_account</tt>.
1250  
-      # [:order]
1251  
-      #   Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
1252  
-      #   such as <tt>last_name, first_name DESC</tt>.
1253 1205
       # [:dependent]
1254 1206
       #   If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
1255 1207
       #   <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
@@ -1262,14 +1214,8 @@ def has_many(name, scope = nil, options = {}, &extension)
1262 1214
       #   will use "person_id" as the default <tt>:foreign_key</tt>.
1263 1215
       # [:primary_key]
1264 1216
       #   Specify the method that returns the primary key used for the association. By default this is +id+.
1265  
-      # [:include]
1266  
-      #   Specify second-order associations that should be eager loaded when this object is loaded.
1267 1217
       # [:as]
1268 1218
       #   Specifies a polymorphic interface (See <tt>belongs_to</tt>).
1269  
-      # [:select]
1270  
-      #   By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
1271  
-      #   you want to do a join but not include the joined columns, for example. Do not forget to include the
1272  
-      #   primary and foreign keys, otherwise it will raise an error.
1273 1219
       # [:through]
1274 1220
       #   Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
1275 1221
       #   <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
@@ -1283,8 +1229,6 @@ def has_many(name, scope = nil, options = {}, &extension)
1283 1229
       # [:source_type]
1284 1230
       #   Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
1285 1231
       #   association is a polymorphic +belongs_to+.
1286  
-      # [:readonly]
1287  
-      #   If true, the associated object is readonly through the association.
1288 1232
       # [:validate]
1289 1233
       #   If +false+, don't validate the associated object when saving the parent object. +false+ by default.
1290 1234
       # [:autosave]
@@ -1303,12 +1247,12 @@ def has_many(name, scope = nil, options = {}, &extension)
1303 1247
       #   has_one :credit_card, :dependent => :destroy  # destroys the associated credit card
1304 1248
       #   has_one :credit_card, :dependent => :nullify  # updates the associated records foreign
1305 1249
       #                                                 # key value to NULL rather than destroying it
1306  
-      #   has_one :last_comment, :class_name => "Comment", :order => "posted_on"
1307  
-      #   has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
1308  
-      #   has_one :attachment, :as => :attachable
1309  
-      #   has_one :boss, :readonly => :true
1310  
-      #   has_one :club, :through => :membership
1311  
-      #   has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
  1250
+      #   has_one :last_comment, -> { order 'posted_on' }, :class_name => "Comment"
  1251
+      #   has_one :project_manager, -> { where role: 'project_manager' }, :class_name => "Person"
  1252
+      #   has_one :attachment, as: :attachable
  1253
+      #   has_one :boss, readonly: :true
  1254
+      #   has_one :club, through: :membership
  1255
+      #   has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
1312 1256
       def has_one(name, scope = nil, options = {})
1313 1257
         Builder::HasOne.build(self, name, scope, options)
1314 1258
       end
@@ -1355,13 +1299,6 @@ def has_one(name, scope = nil, options = {})
1355 1299
       #   Specify the class name of the association. Use it only if that name can't be inferred
1356 1300
       #   from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
1357 1301
       #   if the real class name is Person, you'll have to specify it with this option.
1358  
-      # [:conditions]
1359  
-      #   Specify the conditions that the associated object must meet in order to be included as a +WHERE+
1360  
-      #   SQL fragment, such as <tt>authorized = 1</tt>.
1361  
-      # [:select]
1362  
-      #   By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed
1363  
-      #   if you want to do a join but not include the joined columns, for example. Do not
1364  
-      #   forget to include the primary and foreign keys, otherwise it will raise an error.
1365 1302
       # [:foreign_key]
1366 1303
       #   Specify the foreign key used for the association. By default this is guessed to be the name
1367 1304
       #   of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
@@ -1394,14 +1331,10 @@ def has_one(name, scope = nil, options = {})
1394 1331
       #   option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
1395 1332
       #   Note: Specifying a counter cache will add it to that model's list of readonly attributes
1396 1333
       #   using +attr_readonly+.
1397  
-      # [:include]
1398  
-      #   Specify second-order associations that should be eager loaded when this object is loaded.
1399 1334
       # [:polymorphic]
1400 1335
       #   Specify this association is a polymorphic association by passing +true+.
1401 1336
       #   Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
1402 1337
       #   to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
1403  
-      # [:readonly]
1404  
-      #   If true, the associated object is readonly through the association.
1405 1338
       # [:validate]
1406 1339
       #   If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
1407 1340
       # [:autosave]
@@ -1422,16 +1355,16 @@ def has_one(name, scope = nil, options = {})
1422 1355
       #   See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
1423 1356
       #
1424 1357
       # Option examples:
1425  
-      #   belongs_to :firm, :foreign_key => "client_of"
1426  
-      #   belongs_to :person, :primary_key => "name", :foreign_key => "person_name"
1427  
-      #   belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
1428  
-      #   belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
1429  
-      #              :conditions => 'discounts > #{payments_count}'
1430  
-      #   belongs_to :attachable, :polymorphic => true
1431  
-      #   belongs_to :project, :readonly => true
1432  
-      #   belongs_to :post, :counter_cache => true
1433  
-      #   belongs_to :company, :touch => true
1434  
-      #   belongs_to :company, :touch => :employees_last_updated_at
  1358
+      #   belongs_to :firm, foreign_key: "client_of"
  1359
+      #   belongs_to :person, primary_key: "name", foreign_key: "person_name"
  1360
+      #   belongs_to :author, class_name: "Person", foreign_key: "author_id"
  1361
+      #   belongs_to :valid_coupon, ->(o) { where "discounts > #{o.payments_count}" },
  1362
+      #                             class_name: "Coupon", foreign_key: "coupon_id"
  1363
+      #   belongs_to :attachable, polymorphic: true
  1364
+      #   belongs_to :project, readonly: true
  1365
+      #   belongs_to :post, counter_cache: true
  1366
+      #   belongs_to :company, touch: true
  1367
+      #   belongs_to :company, touch: :employees_last_updated_at
1435 1368
       def belongs_to(name, scope = nil, options = {})
1436 1369
         Builder::BelongsTo.build(self, name, scope, options)
1437 1370
       end
@@ -1545,47 +1478,6 @@ def belongs_to(name, scope = nil, options = {})
1545 1478
       #   By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
1546 1479
       #   So if a Person class makes a +has_and_belongs_to_many+ association to Project,
1547 1480
       #   the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
1548  
-      # [:conditions]
1549  
-      #   Specify the conditions that the associated object must meet in order to be included as a +WHERE+
1550  
-      #   SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are
1551  
-      #   scoped if a hash is used.
1552  
-      #   <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
1553  
-      #   or <tt>@blog.posts.build</tt>.
1554  
-      # [:order]
1555  
-      #   Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
1556  
-      #   such as <tt>last_name, first_name DESC</tt>
1557  
-      # [:uniq]
1558  
-      #   If true, duplicate associated objects will be ignored by accessors and query methods.
1559  
-      # [:finder_sql]
1560  
-      #   Overwrite the default generated SQL statement used to fetch the association with a manual statement
1561  
-      # [:counter_sql]
1562  
-      #   Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
1563  
-      #   specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
1564  
-      #   replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
1565  
-      # [:delete_sql]
1566  
-      #   Overwrite the default generated SQL statement used to remove links between the associated
1567  
-      #   classes with a manual statement.
1568  
-      # [:insert_sql]
1569  
-      #   Overwrite the default generated SQL statement used to add links between the associated classes
1570  
-      #   with a manual statement.
1571  
-      # [:extend]
1572  
-      #   Anonymous module for extending the proxy, see "Association extensions".
1573  
-      # [:include]
1574  
-      #   Specify second-order associations that should be eager loaded when the collection is loaded.
1575  
-      # [:group]
1576  
-      #   An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
1577  
-      # [:having]
1578  
-      #   Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns.
1579  
-      #   Uses the <tt>HAVING</tt> SQL-clause.
1580  
-      # [:limit]
1581  
-      #   An integer determining the limit on the number of rows that should be returned.
1582  
-      # [:offset]
1583  
-      #   An integer determining the offset from where the rows should be fetched. So at 5,
1584  
-      #   it would skip the first 4 rows.
1585  
-      # [:select]
1586  
-      #   By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
1587  
-      #   you want to do a join but exclude the joined columns, for example. Do not forget to include the primary
1588  
-      #   and foreign keys, otherwise it will raise an error.
1589 1481
       # [:readonly]
1590 1482
       #   If true, all the associated objects are readonly through the association.
1591 1483
       # [:validate]
@@ -1600,12 +1492,10 @@ def belongs_to(name, scope = nil, options = {})
1600 1492
       #
1601 1493
       # Option examples:
1602 1494
       #   has_and_belongs_to_many :projects
1603  
-      #   has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
1604  
-      #   has_and_belongs_to_many :nations, :class_name => "Country"
1605  
-      #   has_and_belongs_to_many :categories, :join_table => "prods_cats"
1606  
-      #   has_and_belongs_to_many :categories, :readonly => true
1607  
-      #   has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
1608  
-      #   proc { |record| "DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}" }
  1495
+      #   has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
  1496
+      #   has_and_belongs_to_many :nations, class_name: "Country"
  1497
+      #   has_and_belongs_to_many :categories, join_table: "prods_cats"
  1498
+      #   has_and_belongs_to_many :categories, -> { readonly }
1609 1499
       def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
1610 1500
         Builder::HasAndBelongsToMany.build(self, name, scope, options, &extension)
1611 1501
       end
577  guides/source/association_basics.textile
Source Rendered
@@ -630,12 +630,12 @@ The <tt>create_<em>association</em></tt> method returns a new object of the asso
630 630
 
631 631
 h5. Options for +belongs_to+
632 632
 
633  
-While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
  633
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this assocation uses two such options:
634 634
 
635 635
 <ruby>
636 636
 class Order < ActiveRecord::Base
637  
-  belongs_to :customer, :counter_cache => true,
638  
-    :conditions => "active = 1"
  637
+  belongs_to :customer, :dependent => :destroy,
  638
+    :counter_cache => true
639 639
 end
640 640
 </ruby>
641 641
 
@@ -643,15 +643,11 @@ The +belongs_to+ association supports these options:
643 643
 
644 644
 * +:autosave+
645 645
 * +:class_name+
646  
-* +:conditions+
647 646
 * +:counter_cache+
648 647
 * +:dependent+
649 648
 * +:foreign_key+
650  
-* +:include+
651 649
 * +:inverse_of+
652 650
 * +:polymorphic+
653  
-* +:readonly+
654  
-* +:select+
655 651
 * +:touch+
656 652
 * +:validate+
657 653
 
@@ -669,16 +665,6 @@ class Order < ActiveRecord::Base
669 665
 end
670 666
 </ruby>
671 667
 
672  
-h6(#belongs_to-conditions). +:conditions+
673  
-
674  
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
675  
-
676  
-<ruby>
677  
-class Order < ActiveRecord::Base
678  
-  belongs_to :customer, :conditions => "active = 1"
679  
-end
680  
-</ruby>
681  
-
682 668
 h6(#belongs_to-counter_cache). +:counter_cache+
683 669
 
684 670
 The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
@@ -737,35 +723,31 @@ end
737 723
 
738 724
 TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
739 725
 
740  
-h6(#belongs_to-includes). +:include+
  726
+h6(#belongs_to-inverse_of). +:inverse_of+
741 727
 
742  
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
  728
+The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options.
743 729
 
744 730
 <ruby>
745  
-class LineItem < ActiveRecord::Base
746  
-  belongs_to :order
  731
+class Customer < ActiveRecord::Base
  732
+  has_many :orders, :inverse_of => :customer
747 733
 end
748 734
 
749 735
 class Order < ActiveRecord::Base
750  
-  belongs_to :customer
751  
-  has_many :line_items
752  
-end
753  
-
754  
-class Customer < ActiveRecord::Base
755  
-  has_many :orders
  736
+  belongs_to :customer, :inverse_of => :orders
756 737
 end
757 738
 </ruby>
758 739
 
759  
-If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
  740
+h6(#belongs_to-polymorphic). +:polymorphic+
760 741
 
761  
-<ruby>
762  
-class LineItem < ActiveRecord::Base
763  
-  belongs_to :order, :include => :customer
764  
-end
  742
+Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
765 743
 
  744
+h6(#belongs_to-touch). +:touch+
  745
+
  746
+If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
  747
+
  748
+<ruby>
766 749
 class Order < ActiveRecord::Base
767  
-  belongs_to :customer
768  
-  has_many :line_items
  750
+  belongs_to :customer, :touch => true
769 751
 end
770 752
 
771 753
 class Customer < ActiveRecord::Base
@@ -773,43 +755,58 @@ class Customer < ActiveRecord::Base
773 755
 end
774 756
 </ruby>
775 757
 
776  
-NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
777  
-
778  
-h6(#belongs_to-inverse_of). +:inverse_of+
779  
-
780  
-The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options.
  758
+In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
781 759
 
782 760
 <ruby>
783  
-class Customer < ActiveRecord::Base
784  
-  has_many :orders, :inverse_of => :customer
785  
-end
786  
-
787 761
 class Order < ActiveRecord::Base
788  
-  belongs_to :customer, :inverse_of => :orders
  762
+  belongs_to :customer, :touch => :orders_updated_at
789 763
 end
790 764
 </ruby>
791 765
 
792  
-h6(#belongs_to-polymorphic). +:polymorphic+
  766
+h6(#belongs_to-validate). +:validate+
793 767
 
794  
-Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
  768
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
795 769
 
796  
-h6(#belongs_to-readonly). +:readonly+
  770
+h5(#belongs_to-scopes_for_belongs_to). Scopes for +belongs_to+
797 771
 
798  
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
  772
+There may be times when you wish to customize the query used by +belongs_to+. Such customizations can be achieved via a scope block. For example:
799 773
 
800  
-h6(#belongs_to-select). +:select+
  774
+<ruby>
  775
+class Order < ActiveRecord::Base
  776
+  belongs_to :customer, -> { where :active => true },
  777
+    :dependent => :destroy
  778
+end
  779
+</ruby>
801 780
 
802  
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
  781
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
803 782
 
804  
-TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
  783
+* +where+
  784
+* +includes+
  785
+* +readonly+
  786
+* +select+
805 787
 
806  
-h6(#belongs_to-touch). +:touch+
  788
+h6(#belongs_to-where). +where+
807 789
 
808  
-If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
  790
+The +where+ method lets you specify the conditions that the associated object must meet.
809 791
 
810 792
 <ruby>
811 793
 class Order < ActiveRecord::Base
812  
-  belongs_to :customer, :touch => true
  794
+  belongs_to :customer, -> { where :active => true }
  795
+end
  796
+</ruby>
  797
+
  798
+h6(#belongs_to-includes). +includes+
  799
+
  800
+You can use the +includes+ method let you specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
  801
+
  802
+<ruby>
  803
+class LineItem < ActiveRecord::Base
  804
+  belongs_to :order
  805
+end
  806
+
  807
+class Order < ActiveRecord::Base
  808
+  belongs_to :customer
  809
+  has_many :line_items
813 810
 end
814 811
 
815 812
 class Customer < ActiveRecord::Base
@@ -817,17 +814,34 @@ class Customer < ActiveRecord::Base
817 814
 end
818 815
 </ruby>
819 816
 
820  
-In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
  817
+If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
821 818
 
822 819
 <ruby>
  820
+class LineItem < ActiveRecord::Base
  821
+  belongs_to :order, -> { includes :customer }
  822
+end
  823
+
823 824
 class Order < ActiveRecord::Base
824  
-  belongs_to :customer, :touch => :orders_updated_at
  825
+  belongs_to :customer
  826
+  has_many :line_items
  827
+end
  828
+
  829
+class Customer < ActiveRecord::Base
  830
+  has_many :orders
825 831
 end
826 832
 </ruby>
827 833
 
828  
-h6(#belongs_to-validate). +:validate+
  834
+NOTE: There's no need to use +includes+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
829 835
 
830  
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
  836
+h6(#belongs_to-readonly). +readonly+
  837
+
  838
+If you use +readonly+, then the associated object will be read-only when retrieved via the association.
  839
+
  840
+h6(#belongs_to-select). +select+
  841
+
  842
+The +select+ method lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
  843
+
  844
+TIP: If you use the +select+ method on a +belongs_to+ association, you should also set the +:foreign_key+ option to guarantee the correct results.
831 845
 
832 846
 h5(#belongs_to-do_any_associated_objects_exist). Do Any Associated Objects Exist?
833 847
 
@@ -924,15 +938,10 @@ The +has_one+ association supports these options:
924 938
 * +:as+
925 939
 * +:autosave+
926 940
 * +:class_name+
927  
-* +:conditions+
928 941
 * +:dependent+
929 942
 * +:foreign_key+
930  
-* +:include+
931 943
 * +:inverse_of+
932  
-* +:order+
933 944
 * +:primary_key+
934  
-* +:readonly+
935  
-* +:select+
936 945
 * +:source+
937 946
 * +:source_type+
938 947
 * +:through+
@@ -956,16 +965,6 @@ class Supplier < ActiveRecord::Base
956 965
 end
957 966
 </ruby>
958 967
 
959  
-h6(#has_one-conditions). +:conditions+
960  
-
961  
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
962  
-
963  
-<ruby>
964  
-class Supplier < ActiveRecord::Base
965  
-  has_one :account, :conditions => "confirmed = 1"
966  
-end
967  
-</ruby>
968  
-
969 968
 h6(#has_one-dependent). +:dependent+
970 969
 
971 970
 If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
@@ -985,30 +984,74 @@ end
985 984
 
986 985
 TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
987 986
 
988  
-h6(#has_one-include). +:include+
  987
+h6(#has_one-inverse_of). +:inverse_of+
989 988
 
990  
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
  989
+The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
991 990
 
992 991
 <ruby>
993 992
 class Supplier < ActiveRecord::Base
994  
-  has_one :account
  993
+  has_one :account, :inverse_of => :supplier
995 994
 end
996 995
 
997 996
 class Account < ActiveRecord::Base
998  
-  belongs_to :supplier
999  
-  belongs_to :representative
  997
+  belongs_to :supplier, :inverse_of => :account
1000 998
 end
  999
+</ruby>
1001 1000
 
1002  
-class Representative < ActiveRecord::Base
1003  
-  has_many :accounts
  1001
+h6(#has_one-primary_key). +:primary_key+
  1002
+
  1003
+By convention, Rails assumes that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
  1004
+
  1005
+h6(#has_one-source). +:source+
  1006
+
  1007
+The +:source+ option specifies the source association name for a +has_one :through+ association.
  1008
+
  1009
+h6(#has_one-source_type). +:source_type+
  1010
+
  1011
+The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
  1012
+
  1013
+h6(#has_one-through). +:through+
  1014
+
  1015
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
  1016
+
  1017
+h6(#has_one-validate). +:validate+
  1018
+
  1019
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
  1020
+
  1021
+h5(#belongs_to-scopes_for_has_one). Scopes for +has_one+
  1022
+
  1023
+There may be times when you wish to customize the query used by +has_one+. Such customizations can be achieved via a scope block. For example:
  1024
+
  1025
+<ruby>
  1026
+class Supplier < ActiveRecord::Base
  1027
+  has_one :account, -> { where :active => true }
1004 1028
 end
1005 1029
 </ruby>
1006 1030
 
1007  
-If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
  1031
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
  1032
+
  1033
+* +where+
  1034
+* +includes+
  1035
+* +readonly+
  1036
+* +select+
  1037
+
  1038
+h6(#has_one-where). +where+
  1039
+
  1040
+The +where+ method lets you specify the conditions that the associated object must meet.
  1041
+
  1042
+<ruby>
  1043
+class Supplier < ActiveRecord::Base
  1044
+  has_one :account, -> { where "confirmed = 1" }
  1045
+end
  1046
+</ruby>
  1047
+
  1048
+h6(#has_one-includes). +includes+
  1049
+
  1050
+You can use the +includes+ method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
1008 1051
 
1009 1052
 <ruby>
1010 1053
 class Supplier < ActiveRecord::Base
1011  
-  has_one :account, :include => :representative
  1054
+  has_one :account
1012 1055
 end
1013 1056
 
1014 1057
 class Account < ActiveRecord::Base
@@ -1021,51 +1064,30 @@ class Representative < ActiveRecord::Base
1021 1064
 end
1022 1065
 </ruby>
1023 1066
 
1024  
-h6(#has_one-inverse_of). +:inverse_of+
1025  
-
1026  
-The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
  1067
+If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
1027 1068
 
1028 1069
 <ruby>
1029 1070
 class Supplier < ActiveRecord::Base
1030  
-  has_one :account, :inverse_of => :supplier
  1071
+  has_one :account, -> { includes :representative }
1031 1072
 end
1032 1073
 
1033 1074
 class Account < ActiveRecord::Base
1034  
-  belongs_to :supplier, :inverse_of => :account
  1075
+  belongs_to :supplier
  1076
+  belongs_to :representative
1035 1077
 end
1036  
-</ruby>
1037  
-
1038  
-h6(#has_one-order). +:order+
1039  
-
1040  
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
1041  
-
1042  
-h6(#has_one-primary_key). +:primary_key+
1043  
-
1044  
-By convention, Rails assumes that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
1045  
-
1046  
-h6(#has_one-readonly). +:readonly+
1047  
-
1048  
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
1049  
-
1050  
-h6(#has_one-select). +:select+
1051  
-
1052  
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
1053  
-
1054  
-h6(#has_one-source). +:source+
1055 1078
 
1056  
-The +:source+ option specifies the source association name for a +has_one :through+ association.
1057  
-
1058  
-h6(#has_one-source_type). +:source_type+
1059  
-
1060  
-The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
  1079
+class Representative < ActiveRecord::Base
  1080
+  has_many :accounts
  1081
+end
  1082
+</ruby>
1061 1083
 
1062  
-h6(#has_one-through). +:through+
  1084
+h6(#has_one-readonly). +readonly+
1063 1085
 
1064  
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
  1086
+If you use the +readonly+ method, then the associated object will be read-only when retrieved via the association.
1065 1087
 
1066  
-h6(#has_one-validate). +:validate+
  1088
+h6(#has_one-select). +select+
1067 1089
 
1068  
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
  1090
+The +select+ method lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
1069 1091
 
1070 1092
 h5(#has_one-do_any_associated_objects_exist). Do Any Associated Objects Exist?
1071 1093
 
@@ -1256,23 +1278,13 @@ The +has_many+ association supports these options:
1256 1278
 * +:as+
1257 1279
 * +:autosave+
1258 1280
 * +:class_name+
1259  
-* +:conditions+
1260 1281
 * +:dependent+
1261  
-* +:extend+
1262 1282
 * +:foreign_key+
1263  
-* +:group+
1264  
-* +:include+
1265 1283
 * +:inverse_of+
1266  
-* +:limit+
1267  
-* +:offset+
1268  
-* +:order+
1269 1284
 * +:primary_key+
1270  
-* +:readonly+
1271  
-* +:select+
1272 1285
 * +:source+
1273 1286
 * +:source_type+
1274 1287
 * +:through+
1275  
-* +:uniq+
1276 1288
 * +:validate+
1277 1289
 
1278 1290
 h6(#has_many-as). +:as+
@@ -1293,75 +1305,124 @@ class Customer < ActiveRecord::Base
1293 1305
 end
1294 1306
 </ruby>
1295 1307
 
1296  
-h6(#has_many-conditions). +:conditions+
  1308
+h6(#has_many-dependent). +:dependent+
  1309
+
  1310
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
  1311
+If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised.
  1312
+
  1313
+NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config.
  1314
+
  1315
+NOTE: This option is ignored when you use the +:through+ option on the association.
1297 1316
 
1298  
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
  1317
+h6(#has_many-foreign_key). +:foreign_key+
  1318
+
  1319
+By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
1299 1320
 
1300 1321
 <ruby>
1301 1322
 class Customer < ActiveRecord::Base
1302  
-  has_many :confirmed_orders, :class_name => "Order",
1303  
-    :conditions => "confirmed = 1"
  1323
+  has_many :orders, :foreign_key => "cust_id"
1304 1324
 end
1305 1325
 </ruby>
1306 1326
 
1307  
-You can also set conditions via a hash:
  1327
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
  1328
+
  1329
+h6(#has_many-inverse_of). +:inverse_of+
  1330
+
  1331
+The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
1308 1332
 
1309 1333
 <ruby>
1310 1334
 class Customer < ActiveRecord::Base
1311  
-  has_many :confirmed_orders, :class_name => "Order",
1312  
-    :conditions => { :confirmed => true }
  1335
+  has_many :orders, :inverse_of => :customer
  1336
+end
  1337
+
  1338
+class Order < ActiveRecord::Base
  1339
+  belongs_to :customer, :inverse_of => :orders
1313 1340
 end
1314 1341
 </ruby>
1315 1342
 
1316  
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
  1343
+h6(#has_many-primary_key). +:primary_key+
  1344
+
  1345
+By convention, Rails assumes that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
  1346
+
  1347
+h6(#has_many-source). +:source+
  1348
+
  1349
+The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
  1350
+
  1351
+h6(#has_many-source_type). +:source_type+
  1352
+
  1353
+The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
  1354
+
  1355
+h6(#has_many-through). +:through+
  1356
+
  1357
+The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has_many-through-association">earlier in this guide</a>.
  1358
+
  1359
+h6(#has_many-validate). +:validate+
  1360
+
  1361
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
1317 1362
 
1318  
-If you need to evaluate conditions dynamically at runtime, use a proc:
  1363
+h5(#has_many-scopes_for_has_many). Scopes for +has_many+
  1364
+
  1365
+There may be times when you wish to customize the query used by +has_many+. Such customizations can be achieved via a scope block. For example:
1319 1366
 
1320 1367
 <ruby>
1321 1368
 class Customer < ActiveRecord::Base
1322  
-  has_many :latest_orders, :class_name => "Order",
1323  
-    :conditions => proc { ["orders.created_at > ?", 10.hours.ago] }
  1369
+  has_many :orders, -> { where :processed => true }
1324 1370
 end
1325 1371
 </ruby>
1326 1372
 
1327  
-h6(#has_many-dependent). +:dependent+
1328  
-
1329  
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
1330  
-If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised.
1331  
-
1332  
-NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config.
  1373
+You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
1333 1374
 
1334  
-NOTE: This option is ignored when you use the +:through+ option on the association.
  1375
+* +where+
  1376
+* +extending+
  1377
+* +group+
  1378
+* +includes+
  1379
+* +limit+
  1380
+* +offset+
  1381
+* +order+
  1382
+* +readonly+
  1383
+* +select+
  1384
+* +uniq+
1335 1385
 
1336  
-h6(#has_many-extend). +:extend+
  1386
+h6(#has_many-where). +where+
1337 1387
 
1338  
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
  1388
+The +where+ method lets you specify the conditions that the associated object must meet.
1339 1389
 
1340  
-h6(#has_many-foreign_key). +:foreign_key+
  1390
+<ruby>
  1391
+class Customer < ActiveRecord::Base
  1392
+  has_many :confirmed_orders, -> { where "confirmed = 1" },
  1393
+    :class_name => "Order"
  1394
+end
  1395
+</ruby>
1341 1396
 
1342  
-By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
  1397
+You can also set conditions via a hash:
1343 1398
 
1344 1399
 <ruby>
1345 1400
 class Customer < ActiveRecord::Base
1346  
-  has_many :orders, :foreign_key => "cust_id"
  1401
+  has_many :confirmed_orders, -> { where :confirmed => true },
  1402
+    :class_name => "Order"
1347 1403
 end
1348 1404
 </ruby>
1349 1405
 
1350  
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
  1406
+If you use a hash-style +where+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
  1407
+
  1408
+h6(#has_many-extending). +extending+
1351 1409
 
1352  
-h6(#has_many-group). +:group+
  1410
+The +extending+ method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
1353 1411
 
1354  
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
  1412
+h6(#has_many-group). +group+
  1413
+
  1414
+The +group+ method supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
1355 1415
 
1356 1416
 <ruby>
1357 1417
 class Customer < ActiveRecord::Base
1358  
-  has_many :line_items, :through => :orders, :group => "orders.id"
  1418
+  has_many :line_items, -> { group 'orders.id' },
  1419
+    :through => :orders
1359 1420
 end
1360 1421
 </ruby>
1361 1422
 
1362  
-h6(#has_many-include). +:include+
  1423
+h6(#has_many-includes). +includes+
1363 1424
 
1364  
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
  1425
+You can use the +includes+ method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
1365 1426
 
1366 1427
 <ruby>
1367