I’m having a problem with a habtm association. I’m not sure if I set
them up wrong or if I’m trying to work with the models incorrectly.
Either way I welcome any clarification on why this isn’t working.
My models look like this:
model/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
[…]
end
role/user.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
My migrations look like this:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :name, :string
[…]
end
end
def self.down
drop_table :users
end
end
class CreateRoles < ActiveRecord::Migration
def self.up
create_table :roles do |t|
t.column :name, :string
t.column :description, :string
end
end
def self.down
drop_table :roles
end
end
class CreateRolesUsers < ActiveRecord::Migration
def self.up
create_table :roles_users do |t|
t.column :id, :number
t.column :role_id, :integer
t.column :user_id, :integer
end
end
def self.down
drop_table :roles_users
end
end
The problem is when I try the following in a migration file I get an
error:
Role.delete_all
superuser = Role.create(
admin = Role.create(
:name => "Admin"
)
content_editor = Role.create(
:name => "Content Editor"
)
news_editor = Role.create(
:name => "News Editor"
)
User.delete_all
michael = User.create(
:name => "michael",
:password => "foo"
)
michael.add_roles(admin)
rebecca = User.create(
:name => "rebecca",
:password => "foobar"
)
rebecca.add_roles(admin)
rebecca.add_roles(content_editor)
rebecca.add_roles(news_editor)
The error is: Mysql::Error: Duplicate entry ‘1’ for key 1: INSERT INTO
roles_users (role_id, id, user_id) VALUES (1, 1, 2)
Thanks in advance if you can help me with this.
Peace,
Mike