Has/belongs to many sql error

I have a model Asset which has_and_belongs_to_many :tags. Tag has only
one field, name. There is a table assets_tags which only has an
asset_id and a tag_id.

I can add a tag to one asset. If I try to add the same tag to another
asset though (asset.tags << tag) I get this error:

Mysql::Error: #23000Duplicate entry ‘4’ for key 1: INSERT INTO
assets_tags (tag_id, id, asset_id) VALUES (4, 4, 1)←[0m

Any ideas what could be causing that? Why does that table have 3 values
(where does ‘id’ come from) when it’s just a join table? Why does the
tag’s id get assigned to this strange ‘id’ column’s value?

Seriously, I add it like this…
asset.tags << tag
asset.save

OK, I guess the join tables always have an id added. But the problem
remains.

Pretty sure the id is your problem, remove it and I bet all will be
well.

you can do this in your migrations:

create_table :my_table_name, :id => false do |t|


end

to avoid the id on join tables in the future

good luck!
Tim

On Aug 30, 1:01 pm, Dave S. [email protected]

Cool, I’ll give it a try. Why is the id there in the first place? Does
rails automatically create a primary key for any create_table call?

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