Aug 20
has_and_belongs_to_many
For anyone learning rails in my wake, here the “Doh!” moments I had as I tried to get many-to-many relationships working. Either it took some digging to find the required information or it wasn’t immediately obvious.
Here’s my list of things I found by trial/error/reading/ and lots of googling (and, yes, it is a verb now.. I’ve been using it as a verb for at least 3 years).
- Put
has_and_belongs_to_manyin each class, naming the other class (it’s table name really… a plural) - Add instances of one class to the collection in the other, e.g.
order.items << album. Do this in only one direction. - Before adding to an object’s collection, save the object. E.g
if order.save order.items << an_itemIt seems that this is only required in the case where
orderis a freshly created object. This makes sense as it will not have anid(for the join table) until it is saved. Furthermore, both objects will have to have been previously saved (i.e. haveids). - The join table is made up of the names of the two related tables.. in alphabetic order. E.g.
items_orders, notorders_items - Don’t put an id column in the join tables. Mine had such a column because I sketched out my schema in a migration, not realizing this.
- In your migrations, use
:id => falseas a second argument tocreate_table, e.g.:create_table :items_orders, :id => false do |t| t.column :item_id, :integer t.column
rder_id, :integer
end
If I’ve missed anything on this list, please let me know and I’ll add it.
Comments Off
