Reputation: 695
I want to add a where on uniqueness validation.
This way it's wrong:
validates :identifier_number, uniqueness: true, if: :is_active?
Only validates when the record I want to validate is active.
I want to "something like this":
validates :identifier_number, uniqueness: proc { where is_active: true }
Validate every record, whether active or not, but only against "active" records. So two inactive records can have the same identifier_number, but no record can have the same indentifier_number as any record that is active.
Upvotes: 0
Views: 80
Reputation: 4415
You can do this by using the following:
validates_uniqueness_of :identifier_number, conditions: -> { where(is_active: true) }
API Docks for this: https://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of
Upvotes: 3
Reputation: 375
You can do it by the following ways
validates :identifier_number, uniqueness: true, if: :is_active?
def is_active?
is_active
end
OR
validates :identifier_number, uniqueness: true,
if: Proc.new { |a| a.is_active }
The rails guide explains it pretty clearly(https://guides.rubyonrails.org/active_record_validations.html).
Hope this helps you!
Upvotes: 0