CodexBloom - Programming Q&A Platform

How to implement a custom validation in Ruby on Rails that checks multiple attributes for uniqueness?

👀 Views: 32 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
ruby rails activerecord Ruby

I tried several approaches but none seem to work. I'm updating my dependencies and I'm trying to implement a custom validation in my Rails 7.1 application that checks the uniqueness of a combination of two attributes in my model. Specifically, I have a `User` model where I want to ensure that the combination of `email` and `username` is unique across all user records. I tried using the standard `validates :attribute, uniqueness: true` method, but it only works for single attributes. Here's what I have so far in my model: ```ruby class User < ApplicationRecord validates :email, presence: true validates :username, presence: true validate :unique_email_and_username_combination def unique_email_and_username_combination if User.exists?(email: email, username: username) errors.add(:base, 'The combination of email and username has already been taken.') end end end ``` While this seems to work in terms of checking the uniqueness, I noticed that it does not perform well when there are a large number of records in the database. I get the following behavior when trying to create a new user with an existing combination: ``` ActiveRecord::RecordNotUnique: PG::UniqueViolation: behavior: duplicate key value violates unique constraint "index_users_on_email_and_username" ``` I also tried adding a unique index in the database: ```ruby database.yml create_table :users do |t| t.string :email t.string :username t.index [:email, :username], unique: true end ``` This doesn't seem to fix the question. Am I implementing the validation correctly, or is there a better way to ensure that the combination is unique? Any suggestions on how to improve the performance of this validation would be greatly appreciated! Is there a better approach? I recently upgraded to Ruby latest.