如何在Ruby on Rails中验证一对ID的唯一性? [英] How do you validate uniqueness of a pair of ids in Ruby on Rails?
本文介绍了如何在Ruby on Rails中验证一对ID的唯一性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设在Ruby中进行以下数据库迁移:
Suppose the following DB migration in Ruby:
create_table :question_votes do |t|
t.integer :user_id
t.integer :question_id
t.integer :vote
t.timestamps
end
进一步假设我希望数据库中的行包含唯一的(user_id,question_id)对.可以在模型中放入合适的粉尘来实现此目的?
Suppose further that I wish the rows in the DB contain unique (user_id, question_id) pairs. What is the right dust to put in the model to accomplish that?
validates_uniqueness_of :user_id, :question_id
似乎只是使行按用户ID唯一,并按问题ID唯一,而不是按行对唯一.
seems to simply make rows unique by user id, and unique by question id, instead of unique by the pair.
推荐答案
validates_uniqueness_of :user_id, :scope => [:question_id]
如果您需要包括另一列(或更多列),则也可以将其添加到范围中.示例:
if you needed to include another column (or more), you can add that to the scope as well. Example:
validates_uniqueness_of :user_id, :scope => [:question_id, :some_third_column]
这篇关于如何在Ruby on Rails中验证一对ID的唯一性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文