【问题标题】: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 应该适合你。

标签: ruby-on-rails validation rspec associations


【解决方案1】:

您应该将allow_nil: true 添加到两个验证中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2022-11-15
    • 2014-09-20
    相关资源
    最近更新 更多