17

这是我期望的一个非常简单的问题,但我无法在指南或其他地方找到明确的答案。

我在 ActiveRecord 上有两个属性。我希望恰好一个存在,另一个为零或空白字符串。

我该如何做相当于 :presence => false 的操作?我想确保该值为零。

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?"

或者也许有一种更优雅的方式来做到这一点......

我正在运行 Rails 3.0.9

4

5 回答 5

37

当且仅当特定属性为 nil 时才允许对象有效,您可以使用“包含”而不是创建自己的方法。

validates :name, inclusion: { in: [nil] }

这是针对 Rails 3 的。Rails 4 解决方案更加优雅:

validates :name, absence: true
于 2015-02-23T23:44:43.043 回答
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?"
于 2012-08-23T14:49:40.850 回答
4

使用自定义验证。

validate :validate_method

# validate if which one required other should be blank
def validate_method
  errors.add(:field, :blank) if condition
end
于 2012-04-10T07:39:19.010 回答
1

看起来 :length => { :is => 0 } 可以满足我的需要。

validates :first_attribute, :length => {:is => 0 }, :unless => "second_attribute.blank?"
于 2012-04-10T07:20:21.563 回答
0

尝试:

validates :first_attribute, :presence => {:if => second_attribute.blank?}
validates :second_attribute, :presence => {:if => (first_attribute.blank? && second_attribute.blank? )}

希望有所帮助。

于 2012-04-09T09:53:53.447 回答