无效的十进制变为0.0 [英] invalid decimal becomes 0.0 in rails

查看:191
本文介绍了无效的十进制变为0.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Rails模型:

I have the following rails model:

class Product < ActiveRecord::Base
end

class CreateProducts < ActiveRecord::Migration
  def self.up
    create_table :products do |t|
      t.decimal :price

      t.timestamps
    end
  end

  def self.down
    drop_table :products
  end
end

但是当我在Rails控制台中执行以下操作时:

But when I do the following in the rails console:

ruby-1.9.2-p180 :001 > product = Product.new
 => #<Product id: nil, price: nil, created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :002 > product.price = 'a'
 => "a" 
ruby-1.9.2-p180 :003 > product.save
 => true 
ruby-1.9.2-p180 :004 > p product
#<Product id: 2, price: #<BigDecimal:39959f0,'0.0',9(9)>, created_at: "2011-05-18 02:48:10", updated_at: "2011-05-18 02:48:10">
 => #<Product id: 2, price: #<BigDecimal:3994ca8,'0.0',9(9)>, created_at: "2011-05-18 02:48:10", updated_at: "2011-05-18 02:48:10"> 

如您所见,我写了"a",它在数据库中保存了0.0.这是为什么?这特别令人讨厌,因为它绕过了我的验证,例如:

As you can see, I wrote 'a' and it saved 0.0 in the database. Why is that? This is particularly annoying because it bypasses my validations e.g.:

class Product < ActiveRecord::Base
  validates :price, :format => /\d\.\d/
end

推荐答案

如果您调用to_f,则将无效的任何内容强制转换为0.0

anything that is invalid gets cast to 0.0 if you call to_f on it

"a".to_f #=> 0.0

您需要使用模型中的验证对其进行检查

you would need to check it with validations in the model

validates_numericality_of :price # at least in rails 2 i think

我不知道按格式进行验证有什么用,所以我无法为您提供帮助,但是尝试验证它是否为数字,仅对照字符串检查RegEx,因此,如果数据库是数字字段,则可能搞砸了

i dont know what validating by format does, so i cant help you there, but try to validate that it is a number, RegExs are only checked against strings, so if the database is a number field it might be messing up

:format用于诸如电子邮件地址,登录名,姓名等检查不合法字符等的内容

:format is for stuff like email addresses, logins, names, etc to check for illegeal characters and such

这篇关于无效的十进制变为0.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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