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>

...

4

1 回答 1

1

见下文。你的检查应该是 on 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
于 2012-11-27T08:58:31.733 回答