简体   繁体   English

Rails 4 /验证-数字:'integer'属性是否需要{only_integer:true}?

[英]Rails 4/ validations - numericality: { only_integer: true } necessary on 'integer' attribute?

I had this on my models: 我在模型上有这个:

validates :deal_sector_id,
              presence: true,
              numericality: { only_integer: true }

deal_sector_id is a integer postgresql column. deal_sector_id是整数的postgresql列。

I'm starting to doubt that numericality: { only_integer: true } is necessary in my validations, as when I upgraded to shoulda-matchers 3.0, I get this error message : 我开始怀疑在验证中是否必须使用数字:{only_integer:true},因为当我升级到Shoulda-matchers 3.0时,会收到以下错误消息:

You are attempting to use validate_numericality_of, but the attribute
       you're testing, :deal_sector_id, is an integer column. One of the
       things that the numericality matcher does is to assert that setting
       :deal_sector_id to a string that doesn't look like an integer will
       cause your deal to become invalid. In this case, it's impossible to
       make this assertion since :deal_sector_id will typecast any incoming
       value to an integer. This means that it's already guaranteed to be
       numeric! Since this matcher isn't doing anything, you can remove it
       from your model tests, and in fact, you can remove the validation from
       your model as it isn't doing anything either.

As you read above, it says "... and in fact, you can remove the validation from your model as it isn't doing anything either." 正如您在上面所阅读的,它说:“……实际上,您也可以从模型中删除验证,因为它也不做任何事情。”

Should I use numericality: { only_integer: true } on 'integer' database tables' columns? 我应该在“整数”数据库表的列上使用数字:{only_integer:true}吗?

The validation helper numericality is intended for String values ( VARCHAR from Postgres), and it will match them against a regular expression. 验证帮助程序numericality用于String值(Postgres的VARCHAR ),并将其与正则表达式匹配。

You're therefore correct in saying that it's not required for native Integer values from the DB. 你因此说,它不是必需的天然正确的Integer从DB值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM