gpt4 book ai didi

ruby-on-rails - Rails 3 在使用查找时验证包含(如何处理或 lambda)

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:47 24 4
gpt4 key购买 nike

我有一个项目,其中有一个 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 } - 但随后收到对象未响应包含的错误?

最佳答案

只需使用一个过程,就像这样:

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

关于ruby-on-rails - Rails 3 在使用查找时验证包含(如何处理或 lambda),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5034988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com