Help with join tables and has_and_belongs_to_many

Hi,

I have a user model and a privilege model. They have the
has_and_belongs_to_many relationship. Here are the model defs:

class User < ActiveRecord::Base
belongs_to :status
has_and_belongs_to_many :privileges
end

class Privilege < ActiveRecord::Base
has_and_belongs_to_many :users
end

Now I have a migration script to create the join table and populate a
few users with some privileges…

class CreateAndInitPrivileges < ActiveRecord::Migration
def self.up
create_table :privileges_users do |t|
t.column :user_id, :integer, :null => false
t.column :privilege_id, :integer, :null =>false
end

admin_priv = Privilege.find_by_name('admin')
user_priv = Privilege.find_by_name('user')

admin_user = User.find_by_email('[email protected]')
admin_user.privileges << admin_priv
admin_user.privileges << user_priv

anon_user = User.find_by_email('[email protected]')
anon_user.privileges << user_priv  # BOMB HERE

end

def self.down
drop_table :privileges_users
end
end

The line
anon_user.privileges << user_priv
bombs because Rails tries to insert a row into privileges_users table
with id of 1, but that id is already taken because of the previous
admin_user.privileges << admin_priv
admin_user.privileges << user_priv
calls.

What’s going on? Why is Rails not using the next highest id?

Thanks for the help,
– Christopher

On 11/9/06, Christopher J. Bottaro [email protected] wrote:

What’s going on? Why is Rails not using the next highest id?

I do not know the why of it, but I hit it myself a few days ago.
Unless you really need that id column in the privileges table, use

create_table(:privileges_users, :id=>false) do |t|
t.column :user_id, :integer, :null => false
t.column :privilege_id, :integer, :null =>false
end

The table will be created without the id column and your inserts will
work.

Awesome, that worked perfectly! And to think I was about to turn in
for the night… :wink:

Thank you very much.