Method: ActiveRecord::Associations::ClassMethods#has_and_belongs_to_many

Defined in:
activerecord/lib/active_record/associations.rb

#has_and_belongs_to_many(name, scope = nil, **options, &extension) ⇒ Object

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” precedes “P” alphabetically. 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. If your tables share a common prefix, it will only appear once at the beginning. For example, the tables “catalog_categories” and “catalog_products” generate a join table name of “catalog_categories_products”.

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[8.0]
  def change
    create_join_table :developers, :projects
  end
end

It’s also a good idea to add indexes to each of those columns to speed up the joins process. However, in MySQL it is advised to add a compound index for both of the columns as MySQL only uses one index per table during the lookup.

Adds the following methods for retrieval and query:

collection is a placeholder for the symbol passed as the name argument, so has_and_belongs_to_many :categories would add among others categories.empty?.

collection

Returns a Relation of all the associated objects. An empty Relation is returned if none are 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). Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record.

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.destroy(object, ...)

Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option. 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 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. Uses the same rules as ActiveRecord::FinderMethods#find.

collection.exists?(...)

Checks whether an associated object with the given conditions exists. Uses the same rules as ActiveRecord::FinderMethods#exists?.

collection.build(attributes = {})

Returns a new object of the collection type that has been instantiated with attributes and 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.reload

Returns a Relation of all of the associated objects, forcing a database read. An empty Relation is returned if none are found.

Example

class Developer < ActiveRecord::Base
  has_and_belongs_to_many :projects
end

Declaring has_and_belongs_to_many :projects adds the following methods (and more):

developer = Developer.find(11)
project   = Project.find(9)

developer.projects
developer.projects << project
developer.projects.delete(project)
developer.projects.destroy(project)
developer.projects = [project]
developer.project_ids
developer.project_ids = [9]
developer.projects.clear
developer.projects.empty?
developer.projects.size
developer.projects.find(9)
developer.projects.exists?(9)
developer.projects.build  # similar to Project.new(developer_id: 11)
developer.projects.create # similar to Project.create(developer_id: 11)
developer.projects.reload

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

Scopes

You can pass a second argument scope as a callable (i.e. proc or lambda) to retrieve a specific set of records or customize the generated query when you access the associated collection.

Scope examples:

has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) }
has_and_belongs_to_many :categories, ->(post) {
  where("default_category = ?", post.default_category)
}

Extensions

The extension argument allows you to pass a block into a has_and_belongs_to_many association. This is useful for adding new finders, creators, and other factory-type methods to be used as part of the association.

Extension examples:

has_and_belongs_to_many :contractors do
  def find_or_create_by_name(name)
    first_name, last_name = name.split(" ", 2)
    find_or_create_by(first_name: first_name, last_name: last_name)
  end
end

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 :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 to Project will use “person_id” as the default :foreign_key.

Setting the :foreign_key option prevents automatic detection of the association’s inverse, so it is generally a good idea to set the :inverse_of option as well.

: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_many association to Project, the association will use “project_id” as the default :association_foreign_key.

:validate

When set to true, validates new objects added to association when saving the parent object. true by default. If you want to ensure associated objects are revalidated on every update, use validates_associated.

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

Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets :autosave to true.

:strict_loading

Enforces strict loading every time an associated record is loaded through this association.

Option examples:

has_and_belongs_to_many :projects
has_and_belongs_to_many :projects, -> { includes(: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 }
has_and_belongs_to_many :categories, strict_loading: true


1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
# File 'activerecord/lib/active_record/associations.rb', line 1870

def has_and_belongs_to_many(name, scope = nil, **options, &extension)
  habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self)

  builder = Builder::HasAndBelongsToMany.new name, self, options

  join_model = builder.through_model

  const_set join_model.name, join_model
  private_constant join_model.name

  middle_reflection = builder.middle_reflection join_model

  Builder::HasMany.define_callbacks self, middle_reflection
  Reflection.add_reflection self, middle_reflection.name, middle_reflection
  middle_reflection.parent_reflection = habtm_reflection

  include Module.new {
    class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def destroy_associations
        association(:#{middle_reflection.name}).delete_all(:delete_all)
        association(:#{name}).reset
        super
      end
    RUBY
  }

  hm_options = {}
  hm_options[:through] = middle_reflection.name
  hm_options[:source] = join_model.right_reflection.name

  [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend, :strict_loading].each do |k|
    hm_options[k] = options[k] if options.key? k
  end

  has_many name, scope, **hm_options, &extension
  _reflections[name].parent_reflection = habtm_reflection
end