zolter
zolter

Reputation: 7160

Rails validates uniqueness with repetitions

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:

  1. Create validates_uniqueness_of with params?
  2. Or create custom validation?

I would be grateful for examples.

Upvotes: 0

Views: 171

Answers (1)

bdon
bdon

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

Related Questions