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