How to Create Many to Many Relationships in Ruby on Rails
July 7, 2007 – 9:23 pmHere is a step by step tutorial on how to create a many-to-many relationships with Ruby on Rails using migrations.
1. Create the first table
ruby script/generate model [first_table]- Edit the migration to contain the columns you need
2. Create the second table
ruby script/generate model [second_table]- Edit the migration to contain the columns you need, and then add the following to the same file:
create_table :[first_table](plural)_[second_table](plural), :id =>; false do |t|
t.column :[second_table]_id, :integer
t.column :[first_table]_id, :integer
end
add_index :[first_table](plural)_second_table(plural), [:[second_table]_id, :[first_table]_id]
add_index :[first_table](plural)_[second_table](plural), :[first_table]_id
3. Update the database
rake db:migrate
4. Update the models
vi app/models/[first_table].rb
Add the following line to the class:
has_and_belongs_to_many :[second_table](plural)
vi app/models/[second_table].rb
Add the following line to the class:
has_and_belongs_to_many :[first_table](plural)
5 Responses to “How to Create Many to Many Relationships in Ruby on Rails”
Looks nice! But the HTML tags within the code are a bit distracting.
By Jesse on Jul 10, 2007
Thanks for letting me know. The formatting was destroyed when I added this new code formatting plugin for wordpress. It should be fine now.
By ethomas on Jul 10, 2007
“It should be fine now”
no is not… i had the same problem blogging on blogspot… at the end i pasted my code on pastie, is far better formatting my code, but has the problem that the reader has to open another window to see my code:
http://pastie.caboo.se/74837
(that was my first pastie
)
Cheers!
Emmanuel
By emmanuel oga on Jul 11, 2007
I agree, it would have been a lot easier if you had given us an example first table and second table, instead of using the words first table and second table. That would have removed the entire difficulty.
However, thanks,it’s hard to find someone who creates the migration file.
By joseph on Mar 13, 2008
>script/generate model Person name:string
>script/generate model Address street:string city:string
>script/generate migration create_people_addresses
– db/migrate/20090518155416_create_people_addresses.rb –
create_table people_addresses, :id =>; false do |t|
t.integer :person_id
t.integer :address_id
end
add_index people_addresses, [person_id, address_id]
add_index people_addresses, people_id
>rake db:migrate
– app/models/person.rb –
has_and_belongs_to_many addresses
– app/models/address.rb –
has_and_belongs_to_many people
By david on May 18, 2009