2012-04-09 106 views
12

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

我在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

+0

我不知道你所需要的:存在=>假都在代码的最后两行。 – creativetechnologist 2012-04-09 09:36:48

+0

@creativetechnologist它需要某种测试。如果我摆脱:存在验证,它给了我:C:/Ruby192/lib/ruby/gems/1.9.1/gems/activemodel-3。在验证中:你需要提供至少一个验证(ArgumentError) – LikeMaBell 2012-04-10 07:10:08

+6

值得注意Rails 4这叫做validates_absence_of。 – mpowered 2014-12-11 00:52:13

回答

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

尝试:

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

希望可以帮助。

1

它看起来像︰length => {:is => 0}适用于我需要的。

validates :first_attribute, :length => {:is => 0 }, :unless => "second_attribute.blank?" 
+1

这有错误信息“是错误的长度(应该是0个字符)”。可以添加自定义消息“必须为空”。 'validates:first_attribute,:length => {:is => 0,:message =>“must be blank”},:unless =>“second_attribute.blank?”' – tfentonz 2014-03-06 23:30:16

3

使用自定义验证。

validate :validate_method 

# validate if which one required other should be blank 
def validate_method 
    errors.add(:field, :blank) if condition 
end 
23

对于允许对象是有效的,当且仅当特定的属性是零,你可以用“包容”,而不是创建自己的方法。

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

这是为Rails 3钢轨4解决方案更优雅:

validates :name, absence: true 
相关问题