개발/ROR

[RoR] has_and_belongs_to_many

팥빙구 2015. 1. 8. 15:11

2.6 The has_and_belongs_to_many Association

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
end
 
class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end

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
    end
 
    create_table :parts do |t|
      t.string :part_number
      t.timestamps null: false
    end
 
    create_table :assemblies_parts, id: false do |t|
      t.belongs_to :assembly, index: true
      t.belongs_to :part, index: true
    end
  end
end