0

我正在尝试验证课堂上exchange_rate的格式:Invoice

class Invoice < ActiveRecord::Base

  attr_accessible :currency, :exchange_rate

  validates :exchange_rate, :format => { :with => exchange_rate_format }

  private

  def exchange_rate_format
    if currency != user.preference.base_currency
      DECIMAL_REGEX
    else
      ANOTHER_REGEX
    end
  end

end

问题是:它根本不起作用。我想我需要在Proc这里使用?不过,我从来没有真正弄清楚如何使用它。也许有人可以帮忙。

非常感谢。

4

2 回答 2

1

是的,您需要使用 Proc 或 lambda,以便在运行时调用验证。

validates :exchange_rate, format: { with: ->(invoice) { invoice.exchange_rate_format } }
# Note, I used Ruby 1.9 hash and lambda syntax here.

为此,您需要将方法列表exchange_rate_format移出,private因为我们正在定义一个显式接收器 ( invoice)。protected如果你愿意,你可以做它。或者您可以将条件放入 lambda。

于 2013-09-12T19:01:21.757 回答
1

一种方法是使用自定义验证器:

class Invoice < ActiveRecord::Base
  class ExchangeRateFormatValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      if !value =~ record.exchange_rate_format
        record.errors[attribute] << "your currency is weak sauce"
      end
    end  
  end

  validates :exchange_rate, exchange_rate_format: true

  # make public
  def exchange_rate_format
    if currency != user.preference.base_currency
      DECIMAL_REGEX
    else
     ANOTHER_REGEX
    end
  end
end
于 2013-09-12T19:02:38.153 回答