instance method
has_and_belongs_to_many
Ruby on Rails 2.3.18
Since v2.2.3Signature
has_and_belongs_to_many(association_id, options = {}, &extension)
Specifies a many-to-many relationship with another class. This associates two classes via an intermediate join table. Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of “developers_projects” because “D” outranks “P”. Note that this precedence is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables “paper_boxes” and “papers” to generate a join table name of “papers_paper_boxes” because of the length of the name “paper_boxes”, but it in fact generates a join table name of “paper_boxes_papers”. Be aware of this caveat, and use the custom :join_table option if you need to.
The join table should not have a primary key or a model associated with it. You must manually generate the join table with a migration such as this:
class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration def self.up create_table :developers_projects, :id => false do |t| t.integer :developer_id t.integer :project_id end end def self.down drop_table :developers_projects end end
Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through has_and_belongs_to_many associations. Records returned from join tables with additional attributes will be marked as readonly (because we can’t save changes to the additional attributes). It’s strongly recommended that you upgrade any associations with attributes to a real join model (see introduction).
Adds the following methods for retrieval and query:
- 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 creating associations in the join table (
collection.pushandcollection.concatare aliases to this method). - collection.delete(object, …)
-
Removes one or more objects from the collection by removing their associations from the join table. This does not destroy the objects.
- collection=objects
-
Replaces the collection’s content by deleting and adding objects as appropriate.
- collection_singular_ids
-
Returns an array of the associated objects’ ids.
- collection_singular_ids=ids
-
Replace the collection by the objects identified by the primary keys in
ids. - collection.clear
-
Removes every object from the collection. This does not destroy the objects.
- collection.empty?
-
Returns
trueif there are no associated objects. - collection.size
-
Returns the number of associated objects.
- collection.find(id)
-
Finds an associated object responding to the
idand that meets the condition that it has to be associated with this object. Uses 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 a new object of the collection type that has been instantiated with
attributesand linked to this object through the join table, but has 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 the join table, and that has already been saved (if it passed the validation).
(collection is replaced with the symbol passed as the first argument, so has_and_belongs_to_many :categories would add among others categories.empty?.)
Example
A Developer class declares has_and_belongs_to_many :projects, which will add:
-
Developer#projects -
Developer#projects<< -
Developer#projects.delete -
Developer#projects= -
Developer#project_ids -
Developer#project_ids= -
Developer#projects.clear -
Developer#projects.empty? -
Developer#projects.size -
Developer#projects.find(id) -
Developer#clients.exists?(...) -
Developer#projects.build(similar toProject.new("project_id" => id)) -
Developer#projects.create(similar toc = Project.new("project_id" => id); c.save; c)
The declaration may 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_and_belongs_to_many :projectswill by default be linked to the Project class, but if the real class name is SuperProject, you’ll have to specify it with this option. - :join_table
-
Specify the name of the join table if the default based on lexical order isn’t what you want. WARNING: If you’re overwriting the table name of either class, the
table_namemethod MUST be declared underneath anyhas_and_belongs_to_manydeclaration in order to work. - :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_and_belongs_to_manyassociation to Project will use “person_id” as the default:foreign_key. - :association_foreign_key
-
Specify the foreign key used for the association on the receiving side of the association. By default this is guessed to be the name of the associated class in lower-case and “_id” suffixed. So if a Person class makes a
has_and_belongs_to_manyassociation to Project, the association will use “project_id” as the default:association_foreign_key. - :conditions
-
Specify the conditions that the associated object must meet in order to be included as a
WHERESQL fragment, such asauthorized = 1. 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 - :uniq
-
If true, duplicate associated objects will be ignored by accessors and query methods.
- :finder_sql
-
Overwrite the default generated SQL statement used to fetch the association with a manual statement
- :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. - :delete_sql
-
Overwrite the default generated SQL statement used to remove links between the associated classes with a manual statement.
- :insert_sql
-
Overwrite the default generated SQL statement used to add links between the associated classes with a manual statement.
- :extend
-
Anonymous 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, for example, you 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. - :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.
trueby default. - :autosave
-
If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
Option examples:
has_and_belongs_to_many :projects has_and_belongs_to_many :projects, :include => [ :milestones, :manager ] has_and_belongs_to_many :nations, :class_name => "Country" has_and_belongs_to_many :categories, :join_table => "prods_cats" has_and_belongs_to_many :categories, :readonly => true has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql => 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
Parameters
-
association_idreq -
optionsopt = {} -
extensionblock
Source
# File activerecord/lib/active_record/associations.rb, line 1215
def has_and_belongs_to_many(association_id, options = {}, &extension)
reflection = create_has_and_belongs_to_many_reflection(association_id, options, &extension)
collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
# Don't use a before_destroy callback since users' before_destroy
# callbacks will be executed after the association is wiped out.
old_method = "destroy_without_habtm_shim_for_#{reflection.name}"
class_eval <<-end_eval unless method_defined?(old_method)
alias_method :#{old_method}, :destroy_without_callbacks # alias_method :destroy_without_habtm_shim_for_posts, :destroy_without_callbacks
def destroy_without_callbacks # def destroy_without_callbacks
#{reflection.name}.clear # posts.clear
#{old_method} # destroy_without_habtm_shim_for_posts
end # end
end_eval
add_association_callbacks(reflection.name, options)
end
Defined in activerecord/lib/active_record/associations.rb line 1215
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Associations::ClassMethods