Validating uniqueness of pair in Ruby on Rails’ Active Record

Hassan Serrano Saade
1 min readAug 21, 2020

I’m doing a challenge today where:

“A dose must have a description, a cocktail and an ingredient, and [cocktail, ingredient] pairings should be unique.”

To do so, we need to use uniqueness validator with scope:

class Dose < ApplicationRecord
belongs_to :cocktail
belongs_to :ingredient
validates :description, presence: true
validates :cocktail, uniqueness: { scope: :ingredient }
end

Also would work with

class Dose < ApplicationRecord
belongs_to :cocktail
belongs_to :ingredient
validates :description, presence: true
validates_uniqueness_of :cocktail, scope::ingredient
end

Flexible, right?.. Loving Ruby on Rails!

--

--