ruby-on-rails - Rails 4/验证 - 数值 : { only_integer: true } necessary on 'integer' attribute?

标签 ruby-on-rails postgresql ruby-on-rails-4 rspec shoulda

我的模型上有这个:

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

deal_sector_id 是一个整数 postgresql 列。

我开始怀疑 numericity: { 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.

正如您在上面读到的,它说“......事实上,您可以从模型中删除验证,因为它也没有做任何事情。”

我应该在“整数”数据库表的列上使用 numericity: { only_integer: true } 吗?

最佳答案

验证助手 numericality适用于 String 值(来自 Postgres 的 VARCHAR),并且它将它们与正则表达式进行匹配。

因此,您的说法是正确的,数据库中的 native Integer不需要需要它。

关于ruby-on-rails - Rails 4/验证 - 数值 : { only_integer: true } necessary on 'integer' attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324699/

相关文章:

postgresql - 如何查询 JSONB 数组?

ruby-on-rails - rails : Authenticate before routing

sql - 使用 Rails 在 Postgres 中开发自定义函数

ruby-on-rails - 正确关联 Ruby on Rails

sql - postgresql 8.2 中的嵌套事务?

ruby-on-rails - ActionController::RoutingError(没有路由匹配 [GET] "/assets/blah.png") Heroku

ruby-on-rails - oracle_enhanced 适配器上的 has_and_belongs_to_many

ruby-on-rails - RSpec Controller 测试错误: controller does not implement method

ruby-on-rails - Grails hasMany并属于与RoR的比较

php - 通过 PHP 导入一些 PostgreSQL 数据时出错