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
On 8/31/07, Bob Showalter
<showaltb-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:>
>
> On 8/31/07, Mariko C.
<rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:
> >
> > So I''m playing around with models right now, and according to
the Agile
> > Web Development 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?
>
> 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.
>
> >
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---