【问题标题】:Rails 3 validates inclusion of when using a find (how to proc or lambda)Rails 3 在使用 find 时验证包含(如何 proc 或 lambda)
【发布时间】:2011-06-29 10:20:47
【问题描述】:

我有一个项目,其中有一个 CURRENCY 和 COUNTRY 表。有一个 PRICE 模型需要有效的货币和国家代码,所以我有以下验证:

validates :currency_code, :presence => true, :inclusion => { :in => Currency.all_codes }
validates :country_code, :presence => true, :inclusion => { :in => Country.all_codes }

all_codes 方法返回一个仅包含货币或国家代码的数组。这有效 只要没有代码添加到表中就可以了。

您将如何编写此代码以使 Currency.all_codes 的结果是 Proc 或在 lambda 内?我尝试了 Proc.new { Currency.all_codes } - 但随后得到一个错误,即对象不响应包含?

【问题讨论】:

  • all_codes 使用的当前代码是什么?
  • def self.all_codes all.collect(&:CURRENCY_CODE) end

标签: ruby-on-rails ruby validation activerecord


【解决方案1】:

只需使用 proc,如下所示:

validates :currency_code,
          :presence => true,
          :inclusion => { :in => proc { Currency.all_codes } }
validates :country_code,
          :presence => true,
          :inclusion => { :in => proc { Country.all_codes } }

对于可能偶然发现这一点的任何其他人来说,值得注意的是,proc 还具有可作为参数访问的记录。所以你可以这样做:

validates :currency_code,
          :presence => true,
          :inclusion => { :in => proc { |record| record.all_codes } }

def all_codes
  ['some', 'dynamic', 'result', 'based', 'upon', 'the', 'record']
end

【讨论】:

  • lambda 也可以访问记录吗?
  • 是的,lambda 是一种 proc(参见 here),因此它也可以访问记录。
  • 将记录作为参数访问 proc 解决了我遇到的问题。在 Article 类中使用 Rolify,属于带有作者和编辑的 Column 类:validates :column, inclusion: { in: proc{ |article| Column.with_role([:author, :editor], article.user) } }
【解决方案2】:

注意:这个答案对于旧版本的 Rails 是正确的,但对于 Rails 3.1 及更高版本,procs 是可以接受的。

它不能接受 Procs。您可以使用自定义验证方法来做同样的事情:

validate :currency_code_exists

def currency_code_exists
    errors.add(:base, "Currency code must exist") unless Currency.all_codes.include?(self.currency_code)
end

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多