Rails 3的验证包括使用查找时(如何PROC或lambda) [英] Rails 3 validates inclusion of when using a find (how to proc or lambda)

查看:112
本文介绍了Rails 3的验证包括使用查找时(如何PROC或lambda)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,有一个货币和COUNTRY表。还有,需要一个有效的货币和国家code的定价模型,所以我有以下验证:

I've got a project where there is a CURRENCY and COUNTRY table. There's a PRICE model that requires a valid currency and country code, so I have the following validation:

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

在ALL_ codeS方法只返回该货币或国家codeS的数组。这工作 精细只要没有codeS被添加到表。

The all_codes method returns an array of just the currency or country codes. This works fine so long as no codes are added to the table.

你怎么会写这使得Currency.all_ codeS的结果,要么是一个Proc或λ里面?我试图Proc.new {Currency.all_ codeS} - ?但后来得到一个错误的对象不响应包括

How would you write this so that the result of the Currency.all_codes was either a Proc or inside a lambda? I tried Proc.new { Currency.all_codes } -- but then get an error that the object doesn't respond to include?

推荐答案

注意:这个答案是真正的旧版本的Rails,但Rails的3.1及以上版本,特效被接受

这绝不能接受的特效。您可以使用自定义的验证方法做同样的事情:

It must not accept Procs. You can use a custom validation method to do the same thing:

validate :currency_code_exists

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

这篇关于Rails 3的验证包括使用查找时(如何PROC或lambda)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆