重叠属性对的唯一性验证
Posted
技术标签:
【中文标题】重叠属性对的唯一性验证【英文标题】:Uniqueness validation on overlapping pairs of attributes 【发布时间】:2014-07-22 18:16:38 【问题描述】:class Request < ActiveRecord::Base
belongs_to :artist
belongs_to :user
belongs_to :petition
end
Request
类旨在将艺术家或用户与has_many, through:
关联中的请愿书联系起来。在Request
类中,我想验证请愿/艺术家对是唯一的,请愿/用户对也是唯一的,但用户、艺术家或请愿都不必是唯一的。本质上,它必须满足这个规范:
describe 'Request' do
it 'is unique for a petition and artist pair' do
r1 = Request.new(petition_id: 1, artist_id: 1)
r2 = Request.new(petition_id: 1, artist_id: 2)
r3 = Request.new(petition_id: 1, artist_id: 2)
r4 = Request.new(petition_id: 2, artist_id: 2)
expect(r1.save).to be_truthy
expect(r2.save).to be_truthy
expect(r3.save).to be_falsy
expect(r4.save).to be_truthy
end
it 'is unique for a petition and user pair' do
r1 = Request.new(petition_id: 1, user_id: 1)
r2 = Request.new(petition_id: 1, user_id: 2)
r3 = Request.new(petition_id: 1, user_id: 2)
r4 = Request.new(petition_id: 2, user_id: 2)
expect(r1.save).to be_truthy
expect(r2.save).to be_truthy
expect(r3.save).to be_falsy
expect(r4.save).to be_truthy
end
end
我尝试使用validates_uniquness_of
:
validates_uniqueness_of :artist_id, scope: :petition_id
validates_uniqueness_of :user_id, scope: :petition_id
但是在这两种情况下,规范都不适用于 r2。是否有内置方式来描述我正在寻找的验证,还是我必须编写自定义验证?
【问题讨论】:
我想将unique indexes
添加到DB
应该适合你。
【参考方案1】:
您应该将allow_nil: true
添加到两个验证中。
【讨论】:
以上是关于重叠属性对的唯一性验证的主要内容,如果未能解决你的问题,请参考以下文章