has_and_belongs_to_many association: Rails

The has_and_belongs_to_many Association

A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:

class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies

has_and_belongs_to_many Association Diagram

The corresponding migration might look like this:

class CreateAssembliesAndParts < ActiveRecord::Migration
  def change
    create_table :assemblies do |t|
      t.string :name
      t.timestamps null: false
    create_table :parts do |t|
      t.string :part_number
      t.timestamps null: false
    create_table :assemblies_parts, id: false do |t|
      t.belongs_to :assembly, index: true
      t.belongs_to :part, index: true

Source : http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s