Has and belongs to many problem

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

Is there a reason that you have
t.column :id, :number
in the roles_users table?

i’ve been trying a number of things. i originally had no “id” columns
defined because i didn’t think you needed to create them manually.

On Aug 24, 12:54 am, “Michael Bannister” [email protected]
wrote:

i’ve been trying a number of things. i originally had no “id” columns
defined because i didn’t think you needed to create them manually.

Hi Mike. I think you want this:

class CreateRolesUsers < ActiveRecord::Migration
def self.up
create_table :roles_users, :id => false do |t|
t.column :role_id, :integer
t.column :user_id, :integer
end
end

Essentially, you don’t want to allow ActiveRecord to give your join
tables an id field which is a primary key. For more information, see
my post here:

http://bkocik.net/2007/07/26/habtm-and-the-id-field/

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs