Thursday, 31 January 2008

ActiveRecord error : duplicate key violates unique constraint

I'm currently working (and still exploring) Ruby on Rails for a VoIP services management web portal project.
I frequently stumble upon some doubts about the correct RoR way of doing things - I admit, I tend to do it java style =( - but this one was really driving me crazy...
When creating a new record for a table named "groups", the ActiveRecord was hitting me with the following exception:

«ActiveRecord::StatementInvalid: RuntimeError: ERROR C23505
Mduplicate key violates unique constraint "pk_groups"»

after some "googlening", I manage to solve this. Apparently, the problem was with the expected sequence, from RoR, for that table "groups".
Since the postgresql was returning the correct next sequence number:

# select nextval('groups_group_id_seq');
nextval
---------
17
(1 row)

it was only a matter of resetting the ActiveRecord sequence (on script/console)
>> ActiveRecord::Base.connection.reset_pk_sequence!('groups')
=> "17"