Creating An Extra Association Between Two Tables

Good Friday Everyone :-).

These are my models:

Problem → has_and_belongs_to_many :tags
Tag → has_and_belongs_to_many :problems

Now if a tag does not exist and I create it and associate it to the
problem it works

self.tags << Tag.create(:name => tag)

But if I have the tag already in the DB and just want to link it to
another problem it does not really like me. I do it like this:

self.tags << Tag.find_by_name(tag)

I get the following error:

Mysql::Error: Duplicate entry ‘20’ for key 1: INSERT INTO
problems_tags (tag_id, problem_id, id) VALUES (20, 33, 20)

The problem is basically that it is trying to create a row in
problem_tags with an ‘id’ that already exists. How come it is trying
to do that? How can I prevent it from doing that?

Thanks for your help guys and gals!

John K.
http://www.kopanas.com

============================================================
http://www.soen.info - Index of online software engineering knowledge
http://www.cusec.net - Canadian University Software Engineering
Conference
http://www.soenlive.com - Presentations from CUSEC

On 6/9/06, John K. [email protected] wrote:

self.tags << Tag.create(:name => tag)

The problem is basically that it is trying to create a row in
problem_tags with an ‘id’ that already exists. How come it is trying
to do that? How can I prevent it from doing that?

The HABTM association table should not have an id field. You should
create it with a migration like:

create_table “problems_tags”, :id => false do |t|

end

Right now, your first step should be to remove that column, preferably
with a migration like:

class RemoveProblemsTagsIdColumn < ActiveRecord::Migration
def self.up
remove_column :problems_tags, :id
end

def self.down
add_column :problems_tags, :id, :integer
end
end

Wow, great explanation, and silly mistake on my side. Thanks a lot
for helping me out my friend!

On 9-Jun-06, at 3:50 PM, Alder G. wrote:

problems_tags (tag_id, problem_id, id) VALUES (20, 33, 20)
end
add_column :problems_tags, :id, :integer

http://lists.rubyonrails.org/mailman/listinfo/rails


-Alder


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

John K.
http://www.kopanas.com

============================================================
http://www.soen.info - Index of online software engineering knowledge
http://www.cusec.net - Canadian University Software Engineering
Conference
http://www.soenlive.com - Presentations from CUSEC