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?
============================================================ 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
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
============================================================ 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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.