Conditionally checking boolean uniqueness in Rails

I try to check the uniqueness of the Boolean field, but only when it is true. I have the following defined in my model:

validates_uniqueness_of :org_feed, if: :org_feed

When this check is performed, it generates the following SQL:

SELECT 1 AS one FROM `feeds` WHERE `feeds`.`org_feed` = BINARY 't' LIMIT 1

But this query returns a string when it finds the feed, where is boolean org_feed 0, which is the exact opposite of what it should do. I would expect it to BINARY 't'be simple true, since the field is logical. So, I feel that the request should look like this:

SELECT 1 AS one FROM `feeds` WHERE `feeds`.`org_feed` = true LIMIT 1

Do I need to say somehow that this is a logical field?

+4
source share
1 answer

:

validates :org_feed, uniqueness: true, if: :org_feed_is_true?

def org_feed_is_true?
  org_feed == true
end

http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless .

+6

Source: https://habr.com/ru/post/1539992/


All Articles