Rails + PostgreSQL, duplicate records are being created against rails validation rules
I have a list_users model with fields (id, list_id, user_id) which joins Users w Lists.
In my rails model for Lists I have the following validation to prevent duplicates.
validates_uniqueness_of :user_id, :scope => :list_id
However every now and then a duplicate record is being created in the list_users table in the DB which ends up breaking a lot of things...
=> [#<ListMember id: 37199, user_id: 1203713, list_id: 13651, created_at: "2012-06-04 20:02:11", updated_at: "2012-06-04 20:02:11"> => [#<ListMember id: 37195, user_id: 1203713, list_id: 13651, created_at: "2012-06-04 20:01:40", updated_at: "2012-06-04 20:01:40">
Has anyone seen this before? Thanks
I have seen this before. I don't know if the context is the same for you, but the reason I was seeing this is basically that I was accidentally building two records with the same id pair in memory, running the validations on the two of them, and THEN saving both to the DB. The uniqueness validation didn't catch this because neither record existed in the DB at the point the validation was run. Maybe this is what you're experiencing.
EDIT: Seeing as how close together in time your records were created, I'd say this is likely the case.
Also, you should migrate an index to the db withadd_index :list_users, [:user_id, :list_id]
I can't help with the Rails part, but you should add a unique index at the database level:
ALTER TABLE list_users ADD UNIQUE (list_id, user_id)
Maybe it will help you diagnose the bug in your Rails code.