How do you validate uniqueness of a pair of ids in Ruby on Rails?

前端 未结 6 2054
梦如初夏
梦如初夏 2020-12-04 17:31

Suppose the following DB migration in Ruby:

    create_table :question_votes do |t|
      t.integer :user_id
      t.integer :question_id
      t.integer :vote

          


        
6条回答
  •  悲&欢浪女
    2020-12-04 18:06

    The best way is to use both, since rails isn't 100% reliable when uniqueness validation come thru.

    You can use:

      validates :user_id, uniqueness: { scope: :question_id }
    

    and to be 100% on the safe side, add this validation on your db (MySQL ex)

      add_index :question_votes, [:user_id, :question_id], unique: true
    

    and then you can handle in your controller using:

      rescue ActiveRecord::RecordNotUnique
    

    So now you are 100% secure that you won't have a duplicated value :)

提交回复
热议问题