Leo
Leo

Reputation: 2103

validating uniqueness of field against other fields inside a scope

i have this validation

validates :second_name, uniqueness: { scope: :school_id }

it performs validation so there can be no students in the same school sharing the same second name. but what if i don't want user in certain school who have third_name same as somebody elses second_name? Is there a default option or do i need to write a custom validation mechanism?

Upvotes: 1

Views: 42

Answers (1)

fbelanger
fbelanger

Reputation: 3568

I've recently struggled with this and the solution was very simple:

validates [:second_name, :third_name], uniqueness: { scope: :school_id }

Unlike the array params on the scope that represents a combination, an array of here is either the :second_name or :third_name data unique to the :school_id.

Upvotes: 2

Related Questions