Rails: validate uniqueness of two columns (together)

后端 未结 3 761
自闭症患者
自闭症患者 2020-12-02 06:58

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 07:48

    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
    

提交回复
热议问题