Rails: validate uniqueness of two columns (together)

Ruby on-RailsRuby on-Rails-3Ruby on-Rails-4ActiverecordRails Activerecord

Ruby on-Rails Problem Overview


I have a Release model with medium and country columns (among others). There should not be releases that share identical medium/country combinations.

How would I write this as a rails validation?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can use a uniqueness validation with the scope option.

Also, you should add a unique index to the DB to prevent new records from passing the validations when checked at the same time before being written:

class AddUniqueIndexToReleases < ActiveRecord::Migration
  def change
    add_index :releases, [:country, :medium], unique: true
  end
end



class Release < ActiveRecord::Base
  validates :country, uniqueness: { scope: :medium }
end

Solution 2 - Ruby on-Rails

All the above answers are missing how to validate the uniqueness of multiple attributes in a model. The code below intends to tell how to use multiple attributes in a scope.

validates :country, uniqueness: { scope: [:medium, :another_medium] }

It validates uniqueness of country in all rows with values of medium and another_medium.

Note: Don't forget to add an index on the above column, this insures fast retrieval and adds a DB level validation for unique records.

Update: For adding an index while creating table

t.index [:country, :medium, :another_medium], unique: true

Solution 3 - Ruby on-Rails

You can pass a :scope parameter to your validator like this:

validates_uniqueness_of :medium, scope: :country

See the documentation for some more examples.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackson CunninghamView Question on Stackoverflow
Solution 1 - Ruby on-RailstompaveView Answer on Stackoverflow
Solution 2 - Ruby on-RailsAamirView Answer on Stackoverflow
Solution 3 - Ruby on-RailsK M Rakibul IslamView Answer on Stackoverflow