Has_and_belongs_to_many question

So I’m playing around with models right now, and according to the Agile
Web D. with Rails book, this should express a many to many
relationship:

class Request < ActiveRecord::Base
has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
has_and_belongs_to_many :requests
end

I’ve also created a table called requests_users with columns “user_id”
and “request_id.”

however, when I do this:

request1.users << user
request2.users << user

I get the error “Mysql::Error: Duplicate entry ‘191’ for key 1.”

What’s going on here? Shouldn’t a user be able to be associated with
more than one request?

Thanks in advance.

On 8/31/07, Mariko C. [email protected] wrote:

has_and_belongs_to_many :requests
I get the error “Mysql::Error: Duplicate entry ‘191’ for key 1.”

What’s going on here? Shouldn’t a user be able to be associated with
more than one request?

Looks like you’ve defined user_id as either PRIMARY KEY or UNIQUE in
the database, which you shouldn’t do. The book shows you how to use a
migration to create the join table.

I had this problem a while ago. IIRC, Rails does not automatically
create a
primary key column on HABTM join tables the way it does for a Users
table by
creating a user_id column. You can verify this by executing a ‘SHOW
COLUMNS
FROM requests_users;’ in mysql and checking that there is no
requests_users_id column.

The solution is to do what the previous poster suggested and create a
migration for the join table. In the migration, you should specify the
primary key column and also add indexes on request_id and user_id (as
appropriate):

class CreateRequestsUsers < ActiveRecord::Migration
def self.up
create_table :requests_users do |t|
t.column :request_id, :integer, :allow_null => false
t.column :user_id, :integer, :allow_null => false
t.column :request_user_id, :integer, :allow_null => false
t.primary_key :request_user_id
end
add_index :requests_users, :request_id
add_index :requests_users, :user_id
end

def self.down
remove_index :requests_users, :request_id
remove_index :requests_users, :user_id
drop_table :requests_users
end
end

-Dan