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>
...