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。是否有内置的方法来描述我正在寻找的验证,或者我是否必须编写自定义验证?
答案 0 :(得分:0)
您应该将allow_nil: true
添加到两个验证中。