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