has_and_belongs_to_many(association_id, options = {}, &extension) public

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".

Any additional fields added to the join table will be placed as attributes when pulling records out through has_and_belongs_to_many associations. This is helpful when have information about the association itself that you want available on retrieval. Note that any fields in the join table will override matching field names in the two joined tables. As a consequence, having an "id" field in the join table usually has the undesirable result of clobbering the "id" fields in either of the other two tables.

Adds the following methods for retrieval and query. collection is replaced with the symbol passed as the first argument, so has_and_belongs_to_many :categories would add among others categories.empty?.

  • collection(force_reload = false) - returns an array of all the associated objects. An empty array is returned if none is found.
  • collection<<(object, ...) - adds one or more objects to the collection by creating associations in the join table (collection.push and collection.concat are aliases to this method).
  • collection.push_with_attributes(object, join_attributes) - adds one to the collection by creating an association in the join table that also holds the attributes from join_attributes (should be a hash with the column names as keys). This can be used to have additional attributes on the join, which will be injected into the associated objects when they are retrieved through the collection. (collection.concat_with_attributes is an alias 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 collections content by deleting and adding objects as appropriate.
  • 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 true if there are no associated objects.
  • collection.size - returns the number of associated objects.
  • collection.find(id) - finds an associated object responding to the id and that meets the condition that it has to be associated with this object.

Example: An Developer class declares has_and_belongs_to_many :projects, which will add:

  • Developer#projects
  • Developer#projects<<
  • Developer#projects.push_with_attributes
  • Developer#projects.delete
  • Developer#projects=
  • Developer#project_ids=
  • Developer#projects.clear
  • Developer#projects.empty?
  • Developer#projects.size
  • Developer#projects.find(id)

The declaration may include an options hash to specialize the behavior of the association.

Options are:

  • :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 :projects will 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_name method MUST be declared underneath any has_and_belongs_to_many declaration 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_many association will use "person_id" as the default foreign_key.
  • :association_foreign_key - specify the association foreign key used for the association. By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed. So if the associated class is Project, the has_and_belongs_to_many 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 "WHERE" sql fragment, such as "authorized = 1".
  • :order - specify the order in which the associated objects are returned as a "ORDER BY&quot; sql fragment, such as "last_name, first_name DESC"
  • :uniq - if set to true, duplicate associated objects will be ignored by accessors and query methods
  • :finder_sql - overwrite the default generated SQL used to fetch the association with a manual one
  • :delete_sql - overwrite the default generated SQL used to remove links between the associated classes with a manual one
  • :insert_sql - overwrite the default generated SQL used to add links between the associated classes with a manual one
  • :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.

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 :active_projects, :join_table => 'developers_projects', :delete_sql =>
  'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
Show source
Register or log in to add new notes.
April 21, 2009
7 thanks

Do not forget to add indexes

Don’t forget to add indexes to HATM table:

add_index :developers_projects, [:developer_id, :project_id]
September 25, 2008
4 thanks

has_many :through

It’s is recommended to use has_many :through association instead of has_and_belongs_to_many. has_many :through is better supported and generally easier to work with once you grasp the idea.

June 25, 2008
4 thanks


The created association method also supports the ‘exists?’ method, similar to ActiveRecord::Base#exists?

has_and_belongs_to_many :categories
categories.exist?(1)   # Check whether there's a relation with a Category
                       # object whose id is 1.
categories.exist?(:id => 1)    # ditto
categories.exist?(['id', 1])   # ditto
categories.exist?(:name => 'Anime')
May 6, 2010
1 thank


Be aware that has_and_belongs_to_many saves association to join table immediately after assign. It does NOT wait for my_object.save. Hence if save does not get through validations (or fail for any other reason), associated records will still be in the database.

Here is a nice workaround: http://github.com/TylerRick/has_and_belongs_to_many_with_deferred_save

February 12, 2009
0 thanks

using collection=objects

It will fire one insert query per new record

March 24, 2009
0 thanks

Finding all records WITHOUT associations

(Thanks to someone on the rails IRC channel who gave me this tip.)

Where Users and Events have a habtm relationship, to find all Users that have no events:

User.find(:all, :include => :events, :conditions => { "events_users.event_id" => nil})

(Note that when specifying a condition on a joined table, you have to put the field name in a string rather than a symbol. In the above example, :events_users.event_id will not work.)