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

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

    If using mysql, you can do it in the database using a unique index. It's something like:

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

    This is going to raise an exception when you try to save a doubled-up combination of question_id/user_id, so you'll have to experiment and figure out which exception to catch and handle.

提交回复
热议问题