Rails 3 验证:存在 =>错误的 [英] Rails 3 Validation :presence => false
本文介绍了Rails 3 验证:存在 =>错误的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我期望的一个非常简单的问题,但我无法在指南或其他地方找到明确的答案.
Here's what I expected to be a perfectly straightforward question, but I can't find a definitive answer in the Guides or elsewhere.
我在 ActiveRecord 上有两个属性.我只想要一个存在,另一个是 nil 或空白字符串.
I have two attributes on an ActiveRecord. I want exactly one to be present and the other to be nil or a blank string.
我该如何做相当于 :presence => false 的事情?我想确保该值为零.
How do I do the equivalent of :presence => false? I want to make sure the value is nil.
validates :first_attribute, :presence => true, :if => "second_attribute.blank?"
validates :second_attribute, :presence => true, :if => "first_attribute.blank?"
# The two lines below fail because 'false' is an invalid option
validates :first_attribute, :presence => false, :if => "!second_attribute.blank?"
validates :second_attribute, :presence => false, :if => "!first_attribute.blank?"
或者也许有一种更优雅的方式来做到这一点......
Or perhaps there's a more elegant way to do this...
我正在运行 Rails 3.0.9
I'm running Rails 3.0.9
推荐答案
class NoPresenceValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'must be blank') unless record.send(attribute).blank?
end
end
validates :first_attribute, :presence => true, :if => "second_attribute.blank?"
validates :second_attribute, :presence => true, :if => "first_attribute.blank?"
validates :first_attribute, :no_presence => true, :if => "!second_attribute.blank?"
validates :second_attribute, :no_presence => true, :if => "!first_attribute.blank?"
这篇关于Rails 3 验证:存在 =>错误的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文