ruby-on-rails – 无效小数在rails中变为0.0
发布时间:2020-12-17 02:52:26 所属栏目:百科 来源:网络整理
导读:我有以下rails模型: class Product ActiveRecord::Baseendclass CreateProducts ActiveRecord::Migration def self.up create_table :products do |t| t.decimal :price t.timestamps end end def self.down drop_table :products endend 但是当我在rails控
我有以下rails模型:
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控制台中执行以下操作时: 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,updated_at: "2011-05-18 02:48:10"> 如你所见,我写了’a’,它在数据库中保存了0.0.这是为什么?这特别令人讨厌,因为它绕过了我的验证,例如: class Product < ActiveRecord::Base validates :price,:format => /d.d/ end 解决方法
如果你调用to_f,任何无效的东西都会被强制转换为0.0
“a”.to_f#=> 0.0 您需要在模型中使用验证进行检查 validates_numericality_of:price#至少在rails 2中我认为 我不知道格式有什么验证,所以我无法帮助你,但尝试验证它是一个数字,只检查字符串的RegExs,所以如果数据库是一个数字字段,它可能会弄乱 :格式用于检查电子邮件地址,登录名,姓名等,以检查非法字符等 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |