Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: validate uniqueness of two columns (together)

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?

like image 586
Jackson Cunningham Avatar asked Oct 18 '22 16:10

Jackson Cunningham


1 Answers

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
like image 322
tompave Avatar answered Oct 21 '22 05:10

tompave