看起来很奇怪,对吗?
validates_presence_of [:visa, :mc, :discover, :amex], :if => :credit_card => true
任何输入表示赞赏,在浏览器中出现语法错误。谢谢。
看起来很奇怪,对吗?
validates_presence_of [:visa, :mc, :discover, :amex], :if => :credit_card => true
任何输入表示赞赏,在浏览器中出现语法错误。谢谢。
试试这个
validates :visa, :mc, :discover, :amex, :presence => true, :if => :credit_card?
如果信用卡是一个布尔字段。
否则定义一个方法
def credit_card?
credit_card.present?
end
你也可以用proc来做
validates :visa, :mc, :discover, :amex, :presence => true, :if => Proc.new{|model| model.credit_card.present?}
明白了,虽然很痛苦。而且无论如何都不完美。下一步将是用户只能选择信用卡或支票。jQuery?
模型.rb
validate :check_if_at_least_one_credit_card, :if => "credit_card=='1'"
validate :check_if_check_is_clicked, :if => "check=='1'"
private
def check_if_at_least_one_credit_card
unless mc=="1" || visa=="1" || amex=="1" || discover=="1"
errors.add(:base, "You need to choose at least one credit card type")
end
end
def check_if_check_is_clicked
unless check=="1"
errors.add(:base, "You need to choose check or credit card")
end
end
然后这需要一些清理但按预期工作。
模板.html.haml
%p{ :style => "font-size: 13px; color: #848687;" }= @bulk_order.check=="1" ? 'Check' : ''
%p{ :style => "font-size: 13px; color: #848687;" }= @bulk_order.credit_card=="1" ? 'Credit Card' : ''
%ul
%li{ :style => "font-size: 13px; color: #848687;" }= @bulk_order.discover=="1" ? 'Discover' : ''
%li{ :style => "font-size: 13px; color: #848687;" }= @bulk_order.amex=="1" ? 'American Express' : ''
%li{ :style => "font-size: 13px; color: #848687;" }= @bulk_order.mc=="1" ? 'Mastercard' : ''
%li{ :style => "font-size: 13px; color: #848687;" }= @bulk_order.visa=="1" ? 'Visa' : ''