2012-04-09 28 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 
相關問題