instance method
has_many
Ruby on Rails 3.2.22.5
Since v2.2.3Signature
has_many(name, options = {}, &extension)
Specifies a one-to-many association. The following methods for retrieval and query of collections of associated objects will be added:
- collection(force_reload = false)
-
Returns an array of all the associated objects. An empty array is returned if none are found.
- collection<<(object, …)
-
Adds one or more objects to the collection by setting their foreign keys to the collection’s primary key. Note that this operation instantly fires update sql without waiting for the save or update call on the parent object.
- collection.delete(object, …)
-
Removes one or more objects from the collection by setting their foreign keys to
NULL. Objects will be in addition destroyed if they’re associated with:dependent => :destroy, and deleted if they’re associated with:dependent => :delete_all.If the
:throughoption is used, then the join records are deleted (rather than nullified) by default, but you can specify:dependent => :destroyor:dependent => :nullifyto override this. - collection=objects
-
Replaces the collections content by deleting and adding objects as appropriate. If the
:throughoption is true callbacks in the join models are triggered except destroy callbacks, since deletion is direct. - collection_singular_ids
-
Returns an array of the associated objects’ ids
- collection_singular_ids=ids
-
Replace the collection with the objects identified by the primary keys in
ids. This method loads the models and callscollection=. See above. - collection.clear
-
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, otherwise sets their foreign keys toNULL. If the:throughoption is true no destroy callbacks are invoked on the join models. Join models are directly deleted. - collection.empty?
-
Returns
trueif there are no associated objects. - collection.size
-
Returns the number of associated objects.
- collection.find(…)
-
Finds an associated object according to the same rules as ActiveRecord::Base.find.
- collection.exists?(…)
-
Checks whether an associated object with the given conditions exists. Uses the same rules as ActiveRecord::Base.exists?.
- collection.build(attributes = {}, …)
-
Returns one or more new objects of the collection type that have been instantiated with
attributesand linked to this object through a foreign key, but have not yet been saved. - collection.create(attributes = {})
-
Returns a new object of the collection type that has been instantiated with
attributes, linked to this object through a foreign key, and that has already been saved (if it passed the validation). Note: This only works if the base model already exists in the DB, not if it is a new (unsaved) record!
(Note: collection is replaced with the symbol passed as the first argument, so has_many :clients would add among others clients.empty?.)
Example
Example: A Firm class declares has_many :clients, which will add:
-
Firm#clients(similar toClients.all :conditions => ["firm_id = ?", id]) -
Firm#clients<< -
Firm#clients.delete -
Firm#clients= -
Firm#client_ids -
Firm#client_ids= -
Firm#clients.clear -
Firm#clients.empty?(similar tofirm.clients.size == 0) -
Firm#clients.size(similar toClient.count "firm_id = #{id}") -
Firm#clients.find(similar toClient.find(id, :conditions => "firm_id = #{id}")) -
Firm#clients.exists?(:name => 'ACME')(similar toClient.exists?(:name => 'ACME', :firm_id => firm.id)) -
Firm#clients.build(similar toClient.new("firm_id" => id)) -
Firm#clients.create(similar toc = Client.new("firm_id" => id); c.save; c)
The declaration can also include an options hash to specialize the behavior of the association.
Options
- :class_name
-
Specify the class name of the association. Use it only if that name can’t be inferred from the association name. So
has_many :productswill by default be linked to the Product class, but if the real class name is SpecialProduct, you’ll have to specify it with this option. - :conditions
-
Specify the conditions that the associated objects must meet in order to be included as a
WHERESQL fragment, such asprice > 5 AND name LIKE 'B%'. Record creations from the association are scoped if a hash is used.has_many :posts, :conditions => {:published => true}will create published posts with@blog.posts.createor@blog.posts.build. - :order
-
Specify the order in which the associated objects are returned as an
ORDER BYSQL fragment, such aslast_name, first_name DESC. - :foreign_key
-
Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and “_id” suffixed. So a Person class that makes a
has_manyassociation will use “person_id” as the default:foreign_key. - :primary_key
-
Specify the method that returns the primary key used for the association. By default this is
id. - :dependent
-
If set to
:destroyall the associated objects are destroyed alongside this object by calling theirdestroymethod. If set to:delete_allall associated objects are deleted without calling theirdestroymethod. If set to:nullifyall associated objects’ foreign keys are set toNULLwithout calling theirsavecallbacks. If set to:restrictthis object raises anActiveRecord::DeleteRestrictionErrorexception and cannot be deleted if it has any associated objects.If using with the
:throughoption, the association on the join model must be abelongs_to, and the records which get deleted are the join records, rather than the associated records. - :finder_sql
-
Specify a complete SQL statement to fetch the association. This is a good way to go for complex associations that depend on multiple tables. May be supplied as a string or a proc where interpolation is required. Note: When this option is used,
find_in_collectionis not added. - :counter_sql
-
Specify a complete SQL statement to fetch the size of the association. If
:finder_sqlis specified but not:counter_sql,:counter_sqlwill be generated by replacingSELECT ... FROMwithSELECT COUNT(*) FROM. - :extend
-
Specify a named module for extending the proxy. See “Association extensions”.
- :include
-
Specify second-order associations that should be eager loaded when the collection is loaded.
- :group
-
An attribute name by which the result should be grouped. Uses the
GROUP BYSQL-clause. - :having
-
Combined with
:groupthis can be used to filter the records that aGROUP BYreturns. Uses theHAVINGSQL-clause. - :limit
-
An integer determining the limit on the number of rows that should be returned.
- :offset
-
An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
- :select
-
By default, this is
*as inSELECT * FROM, but can be changed if you, for example, want to do a join but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error. - :as
-
Specifies a polymorphic interface (See
belongs_to). - :through
-
Specifies an association through which to perform the query. This can be any other type of association, including other
:throughassociations. Options for:class_name,:primary_keyand:foreign_keyare ignored, as the association uses the source reflection.If the association on the join model is a
belongs_to, the collection can be modified and the records on the:throughmodel will be automatically created and removed as appropriate. Otherwise, the collection is read-only, so you should manipulate the:throughassociation directly.If you are going to modify the association (rather than just read from it), then it is a good idea to set the
:inverse_ofoption on the source association on the join model. This allows associated records to be built which will automatically create the appropriate join model records when they are saved. (See the ‘Association Join Models’ section above.) - :source
-
Specifies the source association name used by
has_many :throughqueries. Only use it if the name cannot be inferred from the association.has_many :subscribers, :through => :subscriptionswill look for either:subscribersor:subscriberon Subscription, unless a:sourceis given. - :source_type
-
Specifies type of the source association used by
has_many :throughqueries where the source association is a polymorphicbelongs_to. - :uniq
-
If true, duplicates will be omitted from the collection. Useful in conjunction with
:through. - :readonly
-
If true, all the associated objects are readonly through the association.
- :validate
-
If
false, don’t validate the associated objects when saving the parent object. true by default. - :autosave
-
If true, always save the associated objects or destroy them if marked for destruction, when saving the parent object. If false, never save or destroy the associated objects. By default, only save associated objects that are new records.
- :inverse_of
-
Specifies the name of the
belongs_toassociation on the associated object that is the inverse of thishas_manyassociation. Does not work in combination with:throughor:asoptions. See ActiveRecord::Associations::ClassMethods’s overview on Bi-directional associations for more detail.
Option examples:
has_many :comments, :order => "posted_on" has_many :comments, :include => :author has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name" has_many :tracks, :order => "position", :dependent => :destroy has_many :comments, :dependent => :nullify has_many :tags, :as => :taggable has_many :reports, :readonly => true has_many :subscribers, :through => :subscriptions, :source => :user has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new { %Q{ SELECT DISTINCT * FROM people p, post_subscriptions ps WHERE ps.post_id = #{id} AND ps.person_id = p.id ORDER BY p.first_name } }
Parameters
-
namereq -
optionsopt = {} -
extensionblock
Source
# File activerecord/lib/active_record/associations.rb, line 1197
def has_many(name, options = {}, &extension)
Builder::HasMany.build(self, name, options, &extension)
end
Defined in activerecord/lib/active_record/associations.rb line 1197
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Associations::ClassMethods