If you want to define a model for your has_and_belongs_to_many join table, you really need to care, because if your table has an id primary key, then the join will not work.

Imagine that you have two tables Product and Keyword and you want to link these with a product_keywords You will create a migration :


 create_table :product_keywords do |t|
      t.column :product_id, :integer
      t.column :keyword_id, :integer
    end

You need an id because you want easily access the table throught a model


class ProductKeyword < ActiveRecord::Base
  belongs_to :product
  belongs_to :keyword
  # something like voting for keyword in product
  has_many :votes
end

Then if you want to access the keywords with Product model


class Product < ActiveRecord::Base
 has_and_belongs_to_many :keywords, 
:class_name=>"Keyword", 
:join_table=>"product_keywords", 
:foreign_key=>"product_id", 
:association_foreign_key=>"keyword_id"
end

This actually doesn't work! Why? When the SQL statements will ask for the keywords columns, it will get all columns, including product_keywords. Since we have an id for keyword AND for product_keywords, the id results are not clear. We need to force the keywords column only.


class Product < ActiveRecord::Base
 has_and_belongs_to_many :keywords, 
:class_name=>"Keyword", 
:join_table=>"product_keywords", 
:foreign_key=>"product_id", 
:association_foreign_key=>"keyword_id", 
:select=>"keywords.*",
:insert_sql=>'INSERT INTO product_keywords (product_id, keyword_id) VALUES (#{id}, #{record.id})'

end