# Bug with Postgres and/or HABTM?

**URL:** <https://www.ruby-forum.com/t/bug-with-postgres-and-or-habtm/56280>\
**Category:** Rails\
**Created:** [December 2, 2005, 7:34am UTC](https://www.ruby-forum.com/t/bug-with-postgres-and-or-habtm/56280 "2005-12-02T07:34:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![monch1962](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ee59a6/32.png) [@monch1962](https://www.ruby-forum.com/u/monch1962)\
**Post date:** [December 2, 2005, 7:34am UTC](https://www.ruby-forum.com/t/bug-with-postgres-and-or-habtm/56280/1 "2005-12-02T07:34:00Z")

</div>

Hello list,

I think I’ve found a bug in the way Rails is talking to my Postgres DB  
when recording HABTM data.

My join\_table looks like this:  
id serial primary key,  
tablea\_id integer references tablea(id),  
tableb\_id integer references tableb(id),  
other\_attributes…

When Rails writes to join\_table, I’d expect it to do something like:  
INSERT INTO join\_table (tablea\_id, tableb\_id) values (123,456)  
or maybe  
INSERT INTO join\_table (id, tablea\_id, tableb\_id) values  
(nextval(‘join\_table\_seq’), 123, 456)

Instead, it’s doing something like  
INSERT INTO join\_table (id, tablea\_id, tableb\_id) values (123, 123, 456)  
with the result that id isn’t being allowed to default to it’s correct  
serial value, but is instead having the value of tablea\_id written to  
it.

This has an obvious problem; as soon as I try to post a 2nd record to  
join\_table where tablea\_id=123, I get a duplicate key error. The  
value 123 has already been written (incorrectly) to the id field, and  
the 2nd record insertion tries to write a 2nd record with id=123.

I can’t believe nobody’s run into this already, but equally I can’t  
find a defect logged for it at [dev.rubyonrails.com](http://dev.rubyonrails.com) and can’t find  
anything in my code that could be causing it. If no-one’s seen it  
already, I’ll try to reproduce it in as simple a form as possible and  
log a defect for it.

Postgres 8.0.4, running on Gentoo with 2.6.14r2 kernel (for what it’s  
worth)  
Rails 0.14.3

Has anyone seen this before?

Regards

Dave M.

---

<div class="post-metadata">

**Author:** ![monch1962](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ee59a6/32.png) [@monch1962](https://www.ruby-forum.com/u/monch1962)\
**Post date:** [December 2, 2005, 8:15am UTC](https://www.ruby-forum.com/t/bug-with-postgres-and-or-habtm/56280/2 "2005-12-02T08:15:21Z")

</div>

On 12/1/05, David M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Has anyone seen this before?

This bug has been known about since April. See  
[http://dev.rubyonrails.org/ticket/1031](http://dev.rubyonrails.org/ticket/1031). I have a plugin for 0.14.3  
that fixes the issue, assuming your primary key is named id. Let me  
know off list if you are interested in it.
