如何在选择 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>
...