如何在 Ruby on Rails 中验证一对 id 的唯一性? [英] How do you validate uniqueness of a pair of ids in Ruby on Rails?

查看:35
本文介绍了如何在 Ruby on Rails 中验证一对 id 的唯一性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在 Ruby 中进行以下数据库迁移:

<前>create_table :question_votes 做 |t|t.integer :user_idt.integer :question_idt.整数:投票t.时间戳结尾

进一步假设我希望数据库中的行包含唯一的 (user_id, question_id) 对.为实现这一目标,应该在模型中放入什么合适的灰尘?

validates_uniqueness_of :user_id, :question_id

似乎只是让行按用户 id 唯一,按问题 id 唯一,而不是按对唯一.

解决方案

validates_uniqueness_of :user_id, :scope =>[:question_id]

如果您需要包含另一列(或更多),您也可以将其添加到范围中.示例:

validates_uniqueness_of :user_id, :scope =>[:question_id, :some_third_column]

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆