how to pass proc to conditions in validates
-
21-12-2019 - |
Question
How can I write validation for barcode to be unique for all users where is_deleted
is false and same chain?
validates :barcode, uniqueness: { conditions: -> { |record| where(is_deleted: false, chain_id: record.chain_id) } }, if: proc { |u| u.barcode.present? }
what is wrong here?
Thanks.
upd. There can be two users with same barcode with same chain_id, if one of them or both have :is_deleted => true
Solution
validates :barcode, uniqueness: { scope: :chain_id, conditions: ->{ where(is_deleted: false) } }, if: proc { |u| u.barcode.present? && u.active? }
I came up with a solution. Thanks and sorry, its late here and head is not working as expected :)
OTHER TIPS
Rails validation have if
and unless
parameters which allow you to add conditions, you used it to check barcode presence properly, but you can extend it for is_deleted
as well.
As to chain id, I understand that you are interested in scoping.
In your case that would be
validates :barcode, uniqueness: { scope: [:chain_id] }, if: proc { |u| u.barcode.present? && w.is_deleted.false? }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow