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.
Asked
Active
Viewed 1.5k times
3 Answers
22
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
- For Rails 5 use
create_join_table
instead to create that (id-less) table.
-
What is the benefit of using create_join_table? As the "old" syntax still works fine and is imho not less comprehensible. – Felix May 15 '19 at 14:12
-
1@Felix, possibly to avoid adding the odd `, :id => false` – Sully May 15 '19 at 23:33
-
I see. Makes sense. – Felix May 16 '19 at 06:27
3
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

Shiv
- 8,362
- 5
- 29
- 32
-
Thanks for the response, I have read that guide. Like I mentioned to another responder, I was just wondering if the generate model script could handle it in one step, and it looks like it can't so that's fine...would've been nice though. ;p – Kevin Mar 16 '11 at 18:03
-
yeah I dont think it can be done automatically. If I discover a short cut I will post it here :). – Shiv Mar 16 '11 at 21:39
1
Please look at this question first: Creating a many-to-many relationship in Rails 3.
In addition, I would recommend next book "Ruby on Rails 3 Tutorial: Learn Rails by Example" for a better understanding of ActiveRecord
relations.
-
Thanks for the response, I have read the guide that post links to. I was just wondering if the generate model script could handle it in one step, looks like no. – Kevin Mar 16 '11 at 18:00