Ruby on rails多个独特的列

时间:2014-10-26 16:59:34

标签: mysql ruby-on-rails ruby

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

1 个答案:

答案 0 :(得分:3)

这里有两个选项:

分别设置每列的唯一性

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