Kevin
Kevin

Reputation: 151

Generating a model with many to many in Ruby on Rails

Is there a way to generate a Rails model with a many to many relationship predefined? I know how to add it to the Active Record after the fact but it would be nice to have it defined in the DB migration and the Active Record model right off the bat.

Upvotes: 15

Views: 15085

Answers (2)

Sully
Sully

Reputation: 14943

Remember that you do not want an id for the join table, so make sure to add :id => false |t|

create_table assemblies_parts, :id => false do |t|
  t.integer :assembly_id
  t.integer :part_id
end

If you use rails

rails generate model Assemblies_parts assembly:references part:references

you will have two indexes, but what you want is

# Add table index
add_index :assemblies_parts, [:assembly_id, :part_id], :unique => true

UPDATE

Upvotes: 23

Shiv
Shiv

Reputation: 8412

You can use this reference from the Rails Guides.Here is the link. Also you will need to manually create the join table for those models using a migration.

e.g

    create_table :assemblies_parts, :force => true do |t|
      t.integer :assembly_id
      t.integer :part_id
    end

Upvotes: 3

Related Questions