# Has/belongs to many sql error

**URL:** <https://www.ruby-forum.com/t/has-belongs-to-many-sql-error/113414>\
**Category:** Rails\
**Created:** [August 30, 2007, 9:45pm UTC](https://www.ruby-forum.com/t/has-belongs-to-many-sql-error/113414 "2007-08-30T21:45:02Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![dnstevenson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8dc957/32.png) [@dnstevenson](https://www.ruby-forum.com/u/dnstevenson)\
**Post date:** [August 30, 2007, 9:45pm UTC](https://www.ruby-forum.com/t/has-belongs-to-many-sql-error/113414/1 "2007-08-30T21:45:02Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dnstevenson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8dc957/32.png) [@dnstevenson](https://www.ruby-forum.com/u/dnstevenson)\
**Post date:** [August 30, 2007, 10:01pm UTC](https://www.ruby-forum.com/t/has-belongs-to-many-sql-error/113414/2 "2007-08-30T22:01:31Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dnstevenson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8dc957/32.png) [@dnstevenson](https://www.ruby-forum.com/u/dnstevenson)\
**Post date:** [August 30, 2007, 10:18pm UTC](https://www.ruby-forum.com/t/has-belongs-to-many-sql-error/113414/3 "2007-08-30T22:18:45Z")

</div>

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. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![dnstevenson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8dc957/32.png) [@dnstevenson](https://www.ruby-forum.com/u/dnstevenson)\
**Post date:** [August 31, 2007, 4:20am UTC](https://www.ruby-forum.com/t/has-belongs-to-many-sql-error/113414/4 "2007-08-31T04:20:03Z")

</div>

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?
