Rails validations: unique scope

To set up a Rails validation for uniqueness with a scope in Ruby, you can follow these steps:

  1. In your model file (e.g., user.rb), define the validation using the validates method. For example:
class User < ApplicationRecord
  validates :email, uniqueness: { scope: :account_id }
end
  1. The validates method is a class method provided by Rails that allows you to define validations for your model attributes. The uniqueness validation option checks if a record with the specified attribute value already exists in the database.

  2. The scope option is used to specify additional columns that should be used to scope the uniqueness validation. In the example above, the uniqueness of the email attribute will be scoped to the account_id attribute. This means that the email must be unique within each account.

  3. When you try to save a record, Rails will automatically perform the uniqueness validation and add an error to the model's errors collection if the validation fails. You can check for validation errors using the valid? method or the errors attribute. For example:

user = User.new(email: '[email protected]', account_id: 1)
user.valid? # returns true if the model is valid, false otherwise
user.errors[:email] # returns an array of error messages for the email attribute

That's it! You have successfully set up a validation for uniqueness with a scope in Ruby on Rails. This ensures that the combination of the specified attribute values is unique within the specified scope.