rails中的无效小数变为0.0

Thi*_*ago 4 validation model ruby-on-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
Run Code Online (Sandbox Code Playgroud)

但是当我在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,'0.0',9(9)>, created_at: "2011-05-18 02:48:10", updated_at: "2011-05-18 02:48:10"> 
Run Code Online (Sandbox Code Playgroud)

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

class Product < ActiveRecord::Base
  validates :price, :format => /\d\.\d/
end
Run Code Online (Sandbox Code Playgroud)

loo*_*non 5

如果你调用to_f,任何无效的东西都会被强制转换为0.0

"a".to_f #=> 0.0

您需要在模型中使用验证进行检查

validates_numericality_of :price # at least in rails 2 i think

我不知道格式验证的是什么,所以我无法帮助你,但尝试验证它是一个数字,RegExs只检查字符串,所以如果数据库是一个数字字段,它可能会弄乱

:格式用于检查电子邮件地址,登录名,姓名等,以检查非法字符等