Rails: validate uniqueness of two columns (together)

后端 未结 3 760
自闭症患者
自闭症患者 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:40

    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 [:medium, :another_medium], unique: true
    

提交回复
热议问题