July 20, 2010

Rails HasAndBelongsToMany Association With Primary Key Error

When using has_and_belongs_to_many, I ran into this error,
ActiveRecord::HasAndBelongsToManyAssociationWithPrimaryKeyError

Primary key is not allowed in a has_and_belongs_to_many join table (articles_users).

So check the linked-table , articles_users in my case, if there is a pk set by default.

Solution

Put the :id => false to the migration create_table SQL.

create_table :articles_users, :id => false do |t|
  t.integer :article_id
  t.integer :user_id
end
Share on Twitter Share the post
Qihuan Piao

Qihuan Piao

(aka kinopyo) is Chinese based in Tokyo. Software writer. He shares stories inspired him in this blog. His infamous line - "I feel calm when I kill those monsters, or people (in game)" shocks his friends deeply.

He also writes in Japanese and Chinese.