Rails 3条件验证(信用卡):语法错误

时间:2012-05-10 21:49:58

标签: ruby-on-rails validation model e-commerce

看起来奇怪,似乎没错?

validates_presence_of [:visa, :mc, :discover, :amex], :if => :credit_card => true

感谢任何输入,在浏览器中出现语法错误。谢谢。

3 个答案:

答案 0 :(得分:1)

试试这个

validates :visa, :mc, :discover, :amex, :presence => true, :if => :credit_card?

如果信用卡是布尔字段。

否则定义方法

def credit_card?
    credit_card.present?
end

答案 1 :(得分:1)

你也可以用proc

来做
validates :visa, :mc, :discover, :amex, :presence => true, :if => Proc.new{|model| model.credit_card.present?}

答案 2 :(得分:0)

知道了,但这很痛苦。而且无论如何都不完美。下一步是用户只能选择信用卡或支票。 Jquery的?

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

然后这需要一些清理工作,但按预期工作。

template.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' : ''