mysql - Ruby on Rails 多个唯一列

标签 mysql ruby-on-rails ruby

我有 Users 表,其中包含 id、user_name、email、password 列,默认情况下,id 是主键,然后我设置 user_nameemail 是唯一的。不知道多个唯一列是否能保证每列的值不重复,或者唯一列的值加在一起不重复?我的意思是,以下哪种情况是正确的?

最佳答案

这里有两个选项:

分别设置每一列的唯一性

validates :email, uniqueness: true
validates :name, uniqueness: true

最好用例子来解释这个行为

| id | name |   email   |
|–––––––––––––––––––––––|
| 1  | Dave |  d@g.com  |
| 2  | Dave |  d2@g.com | # invalid, as Dave is a duplicate
| 3  | Mary |  m@g.com  | # valid, both values are unique 

将唯一性设置为范围

validates :email, uniqueness: { scope: :name }

例子

| id | name |   email   |
|–––––––––––––––––––––––|
| 1  | Dave |  d@g.com  |
| 2  | Dave |  d2@g.com | # valid, as the combination of Dave & d2@g.com is unique
| 3  | Mary |  m@g.com  | # valid, both values are unique
| 4  | Mary |  m@g.com  | # invalid, as the combination already exists 

关于mysql - Ruby on Rails 多个唯一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26575513/

相关文章:

ruby-on-rails - ROR模型关联问题

php - MySQL php INSERT INTO 需要很长时间

mysql - 给定正方形网格坐标,如何计算属于该范围内的不同表中的数据?

ruby-on-rails - 从特定字符串中提取信息

ruby - 如何将字符串 "*.*"作为命令行参数传递给 ruby​​?

ruby - 无法在 Ruby 中创建 Hash of Hashes

php - 将 Mysql 查询转换为 Laravel 4 Eloquent

mysql - 如何从一个表中选择一列并从另一个表中选择另一列

mysql - Windows 7 中的 Ruby on Rails

ruby-on-rails - 用于生成正则表达式示例的 Ruby gem