Rails 3验证:presence => false

Lik*_*ell 14 validation ruby-on-rails

这是我期望的一个非常直截了当的问题,但我无法在指南或其他地方找到明确的答案.

我在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?"
Run Code Online (Sandbox Code Playgroud)

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

我正在运行Rails 3.0.9

La-*_*eja 32

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

validates :name, inclusion: { in: [nil] }
Run Code Online (Sandbox Code Playgroud)

这适用于Rails 3.Rails 4解决方案更加优雅:

validates :name, absence: true
Run Code Online (Sandbox Code Playgroud)


Kri*_*ris 8

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?"
Run Code Online (Sandbox Code Playgroud)