使用真实命名范围进行验证 rails

validation using real named scopes rails

我有一个 approver_note、po_number 和 state_type 的发票模型。

我需要验证来检查:

scope :approver, where(state_type: 3)
scope :po_no, where(state_type: 2)

validates :approver_note, :presence => true, uniqueness: { scope: [:ac_id, :approver]}, if: :state_three?
validates :po_number, :presence => true, uniqueness: { scope: [:ac_id, :po_no]}, if: :state_two?

def state_three?
    self.state_type==3
end

def state_two?
    self.state_type==2
end

如何确保 approver_note 验证器在选定记录范围内的唯一性是 运行。它应该使用 state_type=3.

的记录进行验证

我需要与此错误类似的内容...

https://rails.lighthouseapp.com/projects/8994/tickets/4325-real-scope-support-for-activerecords-uniqueness-validation

现在 rails 可以使用吗?或者我们可以使用自定义验证来实现吗?

uniqunessscope 选项检查 table 中 2 列值的组合是否唯一应用动态范围。即使 rails !

也太神奇了

但是自定义验证器非常简单:

validate :approver_note_scoped_uniqueness, if: :state_three?

def approver_note_scoped_uniqueness
  if self.class.approver.where(ac_id: ac_id).count > 0
    errors.add(:ac_id, "My custom error message")
  end
end

附加信息:

除此之外,我看到条件选项在 Rails 的 validate_uniqueness_of 中可用。我们可以使用它并构建两个验证,一个用于存在,一个用于唯一性。以防万一有人在 Rails 4.

中寻找答案

在Rails4的情况下,

validates_presence_of :approver_note, if: :state_three?
validates_presence_of :po_number, if: :state_two?
validates_uniqueness_of :approver_note, scope: [:ac_id], conditions: -> { where(state_type: 3)}, if: :state_three?
validates_uniqueness_of :po_number, scope: [:ac_id], conditions: -> { where(state_type: 2)}, if: :state_two?

def state_three?
    self.state_type==3
end

def state_two?
    self.state_type==2
end