Conditionally validating uniqueness of a boolean in Rails
activerecord, rails-activerecord, ruby-on-rails-4
Solution
You can use the following code in your model:
validates :org_feed, uniqueness: true, if: :org_feed
Have a look at http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless for more information about this.
Problem
I'm trying to validate the uniqueness of a boolean field, but only when it's true. I have the following defined in my model: ``` validates_uniqueness_of :org_feed, if: :org_feed ``` When this validation runs, it generates the following SQL: ``` SELECT 1 AS one FROM `feeds` WHERE `feeds`.`org_feed` = BINARY 't' LIMIT 1 ``` But, this query returns a row when it finds a feed where the boolean org_feed is `0`, which is the exact opposite of what it should do. I would expect the `BINARY 't'` to just be `true` since the field is a boolean. Thus, I feel like the query should look like this instead: ``` SELECT 1 AS one FROM `feeds` WHERE `feeds`.`org_feed` = true LIMIT 1 ``` Do I need to tell the validation that this is a boolean field somehow?