Maxim Zubarev
Maxim Zubarev

Reputation: 2473

What do conditions target in uniqueness validators?

I have the following validator in my model:

validates_uniqueness_of :item_id, conditions: -> { where.not(status: "published") }

What does the condition target here? Does it prevent the validator itself to look on the table row if there is status: "published" or is it an extension for the uniqueness validator to exclude the rows with status: "published" in the uniqueness (yes, there is a difference)?

Is there also a difference between the above validator and the following, assuming that status_published? is a method checking for the status to be "published" or not?

validates_uniqueness_of :item_id, :unless => lambda { status_published? }

And finally, if there is no difference, how can I accomplish the second case, where uniqueness validator will check if the value is unique only in the rows which are true for the condition?

Upvotes: 0

Views: 51

Answers (1)

tirdadc
tirdadc

Reputation: 4703

According to the documentation, conditions limit the constraint to the set of records that match them, so the validation doesn't run at all if those said conditions aren't matched.

On a side-note, if you're doing this in Rails 4, you may want to look at the new validates syntax:

validates :item_id, uniqueness: true, unless: :status_published?

Upvotes: 1

Related Questions