Aug 20

has_and_belongs_to_many

dastels @ 2:19 am

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).

  1. Put has_and_belongs_to_many in each class, naming the other class (it’s table name really… a plural)
  2. Add instances of one class to the collection in the other, e.g. order.items << album. Do this in only one direction.
  3. Before adding to an object’s collection, save the object. E.g
    if order.save
      order.items << an_item
    

    It seems that this is only required in the case where order is a freshly created object. This makes sense as it will not have an id (for the join table) until it is saved. Furthermore, both objects will have to have been previously saved (i.e. have ids).

  4. The join table is made up of the names of the two related tables.. in alphabetic order. E.g. items_orders, not orders_items
  5. 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.
  6. In your migrations, use :id => false as a second argument to create_table, e.g.:
    create_table :items_orders, :id => false do |t|
      t.column :item_id, :integer
      t.column :o rder_id, :integer
    end
    

If I’ve missed anything on this list, please let me know and I’ll add it.



Steve Jobs Memorial

Stay Hungry, Stay Foolish!
Steve Jobs

In memory of Steve Jobs