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

前端 未结 6 2043
梦如初夏
梦如初夏 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:09

    Except for writing your own validate method, the best you could do with validates_uniqueness_of is this:

    validates_uniqueness_of :user_id, :scope => "question_id"
    

    This will check that the user_id is unique within all rows with the same question_id as the record you are attempting to insert.

    But that's not what you want.

    I believe you're looking for the combination of :user_id and :question_id to be unique across the database.

    In that case you need to do two things:

    1. Write your own validate method.
    2. Create a constraint in the database because there's still a chance that your app will process two records at the same time.

提交回复
热议问题