I’m very new to Rails and am having trouble with Rails/ActiveRecord seemingly ignoring scope on a validates_uniqueness_of declaration in a project I’ve inherited. I have the following model:
class User < ActiveRecord::Base
…
validates_uniqueness_of :email, scope: :brand_id, allow_nil: true
…
belongs_to :brand
…
end
There is an existing user record with an email of [email protected] and a brand_id of 1.
When trying to update another user record with an id of 123, email of [email protected] and a brand_id of 2, I get a Validation failed: Email has already been taken error.
I see the following two queries run one after the other when this error occurs:
SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[email protected]' AND "users"."id" != 123) LIMIT 1;
SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[email protected]' AND "users"."id" != 123 AND "users"."brand_id" = 2) LIMIT 1;
It looks like the second query is doing the correct uniqueness check, but the first one is ignoring the scope.
Any tips on what to look at or how to debug further would be appreciated.
There's nothing wrong with your logic in the model. There's something else that's stopping the Record to save.
Can you put the whole model?