guides/source/association_basics.textile in railties-3.0.20 vs guides/source/association_basics.textile in railties-3.1.0.beta1

- old
+ new

@@ -28,11 +28,11 @@ </ruby> Or consider deleting a customer, and ensuring that all of its orders get deleted as well: <ruby> -@orders = Order.find_all_by_customer_id(@customer.id) +@orders = Order.where(:customer_id => @customer.id) @orders.each do |order| order.destroy end @customer.destroy </ruby> @@ -63,11 +63,11 @@ To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails. h3. The Types of Associations -In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association: +In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations: * +belongs_to+ * +has_one+ * +has_many+ * +has_many :through+ @@ -163,10 +163,16 @@ class Paragraph < ActiveRecord::Base belongs_to :section end </ruby> +With +:through => :sections+ specified, Rails will now understand: + +<ruby> +@document.paragraphs +</ruby> + h4. The +has_one :through+ Association A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this: <ruby> @@ -221,11 +227,11 @@ The corresponding migration might look like this: <ruby> class CreateSuppliers < ActiveRecord::Migration - def self.up + def change create_table :suppliers do |t| t.string :name t.timestamps end @@ -233,15 +239,10 @@ t.integer :supplier_id t.string :account_number t.timestamps end end - - def self.down - drop_table :accounts - drop_table :suppliers - end end </ruby> NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead. @@ -306,40 +307,32 @@ If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface: <ruby> class CreatePictures < ActiveRecord::Migration - def self.up + def change create_table :pictures do |t| t.string :name t.integer :imageable_id t.string :imageable_type t.timestamps end end - - def self.down - drop_table :pictures - end end </ruby> This migration can be simplified by using the +t.references+ form: <ruby> class CreatePictures < ActiveRecord::Migration - def self.up + def change create_table :pictures do |t| t.string :name t.references :imageable, :polymorphic => true t.timestamps end end - - def self.down - drop_table :pictures - end end </ruby> !images/polymorphic.png(Polymorphic Association Diagram)! @@ -405,21 +398,17 @@ This declaration needs to be backed up by the proper foreign key declaration on the orders table: <ruby> class CreateOrders < ActiveRecord::Migration - def self.up + def change create_table :orders do |t| t.datetime :order_date t.string :order_number t.integer :customer_id end end - - def self.down - drop_table :orders - end end </ruby> If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key. @@ -443,20 +432,16 @@ These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key: <ruby> class CreateAssemblyPartJoinTable < ActiveRecord::Migration - def self.up + def change create_table :assemblies_parts, :id => false do |t| t.integer :assembly_id t.integer :part_id end end - - def self.down - drop_table :assemblies_parts - end end </ruby> We pass +:id => false+ to +create_table+ because that table does not represent a model. That's required for the association to work properly. If you observe any strange behaviour in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit. @@ -548,21 +533,23 @@ customer= build_customer create_customer </ruby> -h6. <tt>_association_(force_reload = false)</tt> +NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix. +h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt> + The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. <ruby> @customer = @order.customer </ruby> If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument. -h6. <tt>_association_=(associate)</tt> +h6(#belongs_to-association_equal). <tt>_association_=(associate)</tt> The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value. <ruby> @order.customer = @customer @@ -635,11 +622,11 @@ class Order < ActiveRecord::Base belongs_to :customer, :conditions => "active = 1" end </ruby> -h6. +:counter_cache+ +h6(#belongs_to-counter_cache). +:counter_cache+ The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models: <ruby> class Order < ActiveRecord::Base @@ -731,11 +718,11 @@ end </ruby> 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. -h6. +:polymorphic+ +h6(#belongs_to-polymorphic). +:polymorphic+ 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>. h6(#belongs_to-readonly). +:readonly+ @@ -745,11 +732,11 @@ 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. 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. -h6. +:touch+ +h6(#belongs_to-touch). +:touch+ 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: <ruby> class Order < ActiveRecord::Base @@ -815,21 +802,23 @@ account= build_account create_account </ruby> -h6. <tt><em>association</em>(force_reload = false)</tt> +NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix. +h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt> + The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. <ruby> @account = @supplier.account </ruby> If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument. -h6. <tt><em>association</em>=(associate)</tt> +h6(#has_one-association_equal). <tt><em>association</em>=(associate)</tt> The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value. <ruby> @supplier.account = @account @@ -1027,10 +1016,11 @@ * <tt><em>collection_singular</em>_ids=ids</tt> * <tt><em>collection</em>.clear</tt> * <tt><em>collection</em>.empty?</tt> * <tt><em>collection</em>.size</tt> * <tt><em>collection</em>.find(...)</tt> +* <tt><em>collection</em>.where(...)</tt> * <tt><em>collection</em>.exists?(...)</tt> * <tt><em>collection</em>.build(attributes = {}, ...)</tt> * <tt><em>collection</em>.create(attributes = {})</tt> In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration: @@ -1052,10 +1042,11 @@ order_ids=ids orders.clear orders.empty? orders.size orders.find(...) +orders.where(...) orders.exists?(...) orders.build(attributes = {}, ...) orders.create(attributes = {}) </ruby> @@ -1081,14 +1072,14 @@ <ruby> @customer.orders.delete(@order1) </ruby> -WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. +WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. -h6(#has_many-collection_equal). <tt><em>collection</em>=objects</tt> +h6(#has_many-collection-equal). <tt><em>collection</em>=objects</tt> The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. h6(#has_many-collection_singular). <tt><em>collection_singular</em>_ids</tt> @@ -1100,54 +1091,65 @@ h6(#has_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt> The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. -h6(#has_many-collection_clear). <tt><em>collection</em>.clear</tt> +h6(#has_many-collection-clear). <tt><em>collection</em>.clear</tt> The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+. -h6. <tt><em>collection</em>.empty?</tt> +h6(#has_many-collection-empty). <tt><em>collection</em>.empty?</tt> The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects. <ruby> <% if @customer.orders.empty? %> No Orders Found <% end %> </ruby> -h6. <tt><em>collection</em>.size</tt> +h6(#has_many-collection-size). <tt><em>collection</em>.size</tt> The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection. <ruby> @order_count = @customer.orders.size </ruby> -h6. <tt><em>collection</em>.find(...)</tt> +h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt> The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. <ruby> -@open_orders = @customer.orders.find(:all, :conditions => "open = 1") +@open_orders = @customer.orders.all(:conditions => "open = 1") </ruby> -h6. <tt><em>collection</em>.exists?(...)</tt> +NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions. +h6(#has_many-collection-where). <tt><em>collection</em>.where(...)</tt> + +The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. + +<ruby> +@open_orders = @customer.orders.where(:open => true) # No query yet +@open_order = @open_orders.first # Now the database will be queried +</ruby> + +h6(#has_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt> + The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+. -h6(#has_many_collection_build). <tt><em>collection</em>.build(attributes = {}, ...)</tt> +h6(#has_many-collection-build). <tt><em>collection</em>.build(attributes = {}, ...)</tt> The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved. <ruby> @order = @customer.orders.build(:order_date => Time.now, :order_number => "A12345") </ruby> -h6. <tt><em>collection</em>.create(attributes = {})</tt> +h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt> The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations). <ruby> @order = @customer.orders.create(:order_date => Time.now, @@ -1191,11 +1193,11 @@ h6(#has_many-as). +:as+ Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>. -h6. +:autosave+ +h6(#has_many-autosave). +:autosave+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. h6(#has_many-class_name). +:class_name+ @@ -1437,15 +1439,16 @@ * <tt><em>collection_singular</em>_ids=ids</tt> * <tt><em>collection</em>.clear</tt> * <tt><em>collection</em>.empty?</tt> * <tt><em>collection</em>.size</tt> * <tt><em>collection</em>.find(...)</tt> +* <tt><em>collection</em>.where(...)</tt> * <tt><em>collection</em>.exists?(...)</tt> * <tt><em>collection</em>.build(attributes = {})</tt> * <tt><em>collection</em>.create(attributes = {})</tt> -In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration: +In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration: <ruby> class Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end @@ -1462,10 +1465,11 @@ assembly_ids=ids assemblies.clear assemblies.empty? assemblies.size assemblies.find(...) +assemblies.where(...) assemblies.exists?(...) assemblies.build(attributes = {}, ...) assemblies.create(attributes = {}) </ruby> @@ -1474,53 +1478,53 @@ If the join table for a +has_and_belongs_to_many+ association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes. WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+. -h6. <tt><em>collection</em>(force_reload = false)</tt> +h6(#has_and_belongs_to_many-collection). <tt><em>collection</em>(force_reload = false)</tt> The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array. <ruby> @assemblies = @part.assemblies </ruby> -h6. <tt><em>collection</em><<(object, ...)</tt> +h6(#has_and_belongs_to_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt> The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table. <ruby> @part.assemblies << @assembly1 </ruby> NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>. -h6. <tt><em>collection</em>.delete(object, ...)</tt> +h6(#has_and_belongs_to_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt> The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects. <ruby> @part.assemblies.delete(@assembly1) </ruby> -h6. <tt><em>collection</em>=objects</tt> +h6(#has_and_belongs_to_many-collection-equal). <tt><em>collection</em>=objects</tt> The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. -h6. <tt><em>collection_singular</em>_ids</tt> +h6(#has_and_belongs_to_many-collection_singular). <tt><em>collection_singular</em>_ids</tt> The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection. <ruby> @assembly_ids = @part.assembly_ids </ruby> -h6. <tt><em>collection_singular</em>_ids=ids</tt> +h6(#has_and_belongs_to_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt> The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. -h6. <tt><em>collection</em>.clear</tt> +h6(#has_and_belongs_to_many-collection-clear). <tt><em>collection</em>.clear</tt> The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects. h6(#has_and_belongs_to_many-collection-empty). <tt><em>collection</em>.empty?</tt> @@ -1543,14 +1547,24 @@ h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)</tt> The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection. <ruby> -@new_assemblies = @part.assemblies.find(:all, +@new_assemblies = @part.assemblies.all( :conditions => ["created_at > ?", 2.days.ago]) </ruby> +NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions. + +h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt> + +The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection. + +<ruby> +@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago) +</ruby> + h6(#has_and_belongs_to_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt> The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+. h6(#has_and_belongs_to_many-collection-build). <tt><em>collection</em>.build(attributes = {})</tt> @@ -1603,11 +1617,11 @@ * +:readonly+ * +:select+ * +:uniq+ * +:validate+ -h6. +:association_foreign_key+ +h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+ By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly: TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example: @@ -1659,11 +1673,11 @@ Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. -h6. +:delete_sql+ +h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+ Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself. h6(#has_and_belongs_to_many-extend). +:extend+ @@ -1697,15 +1711,15 @@ h6(#has_and_belongs_to_many-include). +:include+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. -h6. +:insert_sql+ +h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+ Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself. -h6. +:join_table+ +h6(#has_and_belongs_to_many-join_table). +:join_table+ If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default. h6(#has_and_belongs_to_many-limit). +:limit+ @@ -1819,10 +1833,10 @@ If you have an extension that should be shared by many associations, you can use a named extension module. For example: <ruby> module FindRecentExtension def find_recent - find(:all, :conditions => ["created_at > ?", 5.days.ago]) + where("created_at > ?", 5.days.ago) end end class Customer < ActiveRecord::Base has_many :orders, :extend => FindRecentExtension