Ruby on Rails Join Tables

January 17, 2008

 
No Gravatar

It’s the simple things that seem to cause the most problems. Recently I had a problem with my Has and Belongs to Many relationships in one of my applications.I wanted to add an Offer to an Offer Group without using SQL to directly write to the join table (as my boss put it…just pretend it doesn’t exist). 

I had a list box in my view which would pass my listbox parameters forward. Then, depending on the selection I would either add or remove something from the join table.I kept encountering an error where a record would exist.

After I dropped the ID column from the join table, all was well. Yeah…ID column…seriously!

Here’s the migration I used to create the join table:

1
2
3
4
5
6
7
8
9
10
11
12
class AddOffersOfferGroups < ActiveRecord::Migration
  def self.up
    create_table :offer_groups_offers do |t|
      t.integer :offer_id
      t.integer :offer_group_id
    end
  end
 
  def self.down
    remove_table :offer_groups_offers
  end
end

blog comments powered by Disqus