2012-11-27 82 views
0

您如何驗證只檢查何時選擇PAYMENT_TYPE檢查並僅在選擇PAYMENT_TYPE信用卡時驗證信用卡?基於表單選擇驗證一個表單字段或其他表單字段,但不能同時

class Order < ActiveRecord::Base 
    attr_accessible :check, :creditcard 
    PAYMENT_TYPES = [ "Check", "Credit card" ] 
    validates :creditcard, :presence => { :if => :creditcard? } 
    validates :check, :presence => { :if => :check? } 

    def creditcard? 
    check == nil 
    end 

    def creditcard? 
    creditcard == nil 
    end 
    end 

形式

<%= form_for(@order) do |f| %> 

...

<div class="field"> 
     <%= f.label :pay_type %><br /> 
     <%= f.select :pay_type, Order::PAYMENT_TYPES, 
     prompt: 'Select a payment method' %> 
    </div> 
    <div id="creditcard"> 
     <%= f.label :creditcard, class: "creditcard" %><br /> 
     <%= f.text_field :creditcard, class: "creditcard" %> 
    </div> 
    <div id="check"> 
     <%= f.label :check, class: "check" %><br /> 
     <%= f.text_field :check, class: "check" %> 
    </div> 

...

回答

1

見下文。您的檢查應該在pay_type

class Order < ActiveRecord::Base 
    attr_accessible :check, :creditcard, :pay_type 
    PAYMENT_TYPES = [ "Check", "Credit card" ] 
    validates :creditcard, :presence => true, :if => :creditcard_selected? 
    validates :check, :presence => true, :if => :check_selected? 

    def check_selected? 
     pay_type == "CHECK" 
    end 

    def creditcard_selected? 
     pay_type == "Credit Card" 
    end 
    end