Skip to content

Instantly share code, notes, and snippets.

@nogtini
Created August 15, 2019 17:47
Show Gist options
  • Save nogtini/65488c1d0a456b08bb5a449e72110b0e to your computer and use it in GitHub Desktop.
Save nogtini/65488c1d0a456b08bb5a449e72110b0e to your computer and use it in GitHub Desktop.
AR Uniqueness of Multiple Columns
# https://stackoverflow.com/questions/34424154/rails-validate-uniqueness-of-two-columns-together
# answer 1
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
# answer 2
validates :country, uniqueness: { scope: [:medium, :another_medium] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment