2012-05-08 26 views
4

上的條件我想驗證這兩個屬性的存在:shipping_cost:shipping_cost_anywhere如果屬性:shipping等於true。而如果validates_presence_of如果rails 3.2和mongoid + simple_form

我有這個在我的模型,但不是爲我工作的罰款:

validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true" if :shipping == "true" 

這是我的:運費屬性:

field :shipping, :type => Boolean, :default => "false" 

我該怎麼辦呢?

謝謝!

已編輯。

我使用mongoid和simple_form寶石

+0

請更具體地說明它如何不適合你。這可以更容易地猜出你想表達的內容。 :) – flooooo

+0

謝謝,如果我將字段':shipping'設置爲true,那麼字段':shipping_cost'和':shipping_cost_anywhere'未驗證。 – hyperrjas

回答

4

對我來說,這個問題的解決方法是下一個代碼:

validates :shipping_cost, :shipping_cost_anywhere, :presence => true, :if => :shipping? 

謝謝大家的幫助,但任何答案已爲我工作。謝謝!

0

這裏工作我的代碼me.Call方法上,如果條件而不是比較

validates :prefix, :allow_blank => true, :uniqueness => { :case_sensitive => true } ,:if => :trunk_group_is_originating? 


     def trunk_group_is_originating? 
      if self.direction == "originating" 
      true 
      else 
      false 
      end 
     end 

希望它可以幫助你..... ..

11
validates_presence_of :shipping_costs_anywhere, :if => :should_be_filled_in? 

def should_be_filled_in? 
    shipping_costs_anywhere == "value" 
end 

該方法將在語句中調用時返回true或false。 無需將冒號放在shipping_costs_anywhere前面。

+1

我使用此方法獲得'undefined method should_be_filled_in?對於#' – hyperrjas

+0

該方法應該是should_be_filled_in?而不是should_be_filled_in –

+0

謝謝我已經檢查了這個,但它不適合我。謝謝! – hyperrjas

1

我無法測試它,但我覺得語法更像是:

validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true", :if => "shipping.nil?" 

參見:

http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-validation

+0

您也可以按照其他人的建議來定義方法。順便提一下,我還注意到Rails指南提到存在驗證器忽略:allow_blank選項,但如果這對您有用,我不會爭辯。 –

+0

謝謝,但這不適合我。 – hyperrjas

+0

根據你的問題和後來的評論,如果你想驗證航運是真實的,還是當它不是真實的,我不清楚。要驗證發貨是否正確,請使用':unless'。如果你想驗證什麼時候裝運是不是真的,使用':if'。 –

2

validates現在優於validates_presences_of等。hyperjas提到你可以這樣做:

validates :shipping_cost, 
    :shipping_cost_anywhere, 
    :presence => true, :if => :shipping? 

然而,conditionalizes兩個:shipping_cost:shipping_cost_anywhere整個驗證。爲了更好的可維護性,我更喜歡爲每個屬性聲明一個單獨的validate

更重要的是,您可能會遇到不同情況下的多個驗證(例如一個用於存在,另一個用於長度,格式或值)。你可以這樣做:

validates :shipping_cost, 
    presence: { if: :shipping? }, 
    numericality: { greater_than: 100, if: :heavy? } 

你也可以讓rails評估一個ruby字符串。

validates :shipping_cost, 
    presence: { if: "shipping?" }, 
    numericality: { greater_than: 100, if: "shipping? and heavy?" } 

最後,選擇添加獨立的自定義消息:

validates :shipping_cost, 
    presence: { if: "shipping?", message: 'You forgot the shipping cost.' }, 
    numericality: { greater_than: 100, if: "shipping? and heavy?", message: 'Shipping heavy items is $100 minimum.' } 

等。希望有所幫助。