Reputation: 7160
I want validate uniqueness with a given number of repetitions, for example allowed three users with the same name.
User id: 1, name: "user"
User id: 2, name: "user"
User id: 3, name: "user"
But you can not create a fourth user with the same name. What should I do:
I would be grateful for examples.
Upvotes: 0
Views: 171
Reputation: 2088
You'll need a custom validation, such as
validates :validate_three_maximum
def validate_three_maximum
if User.where(:name => "user").count >= 3 && (new_record? || name_changed?)
errors.add(:name, "Maximum of 3 with this name")
end
end
Be aware that database uniqueness checks in your application are prone to race conditions: See Concurrency and Integrity.
EDIT: added new_record? + name_changed? check as updating a record won't count towards the 3.
Upvotes: 3