Ruby on Rails Models. Why does a decimal{2,1} with

2019-06-13 19:41发布

问题:

I'm having an issue with a table accepting too many digits after the decimal, despite defining it's precision and scope.

rails generate model Hotel name:string 'rating:decimal{2,1}'

class CreateHotels < ActiveRecord::Migration
  def change
    create_table :hotels do |t|
      t.string :name
      t.decimal :rating, precision: 2, scale: 1

      t.timestamps
    end
  end
end

However, I am able to do the following.

Hotel.create!(name: “The Holiday Inn”, rating: 3.75)

Additionally, I have a rooms table (Room model), with

t.decimal :rate, precision: 5, scale: 2 #this holds the room's nightly rate

I input 99.99 into this column, but it ends up storing it as 99.98999999..

Why do I have these 2 decimal issues? If I have defined my scope, why am I allowed to input more scope than I have defined?

回答1:

I input 99.99 into this column, but it ends up storing it as 99.98999999...

That suggests that you're using SQLite which doesn't really have a decimal data type, if you ask SQLite to create a decimal(m,n) column it will create a REAL instead; REAL is a floating point type, not a fixed precision type. To solve this problem, stop using SQLite; odds are that you're not going to deploy a real application on top of SQLite anyway so you should be developing with the same database that you're going to deploy on.

Also, if you're using a fixed precision type for rating, you should not say this:

Hotel.create!(name: "The Holiday Inn", rating: 3.75)

as that 3.75 will be a floating point value in Ruby and it could get messed up before the database sees it. You should say one of these instead:

Hotel.create!(name: "The Holiday Inn", rating: '3.75')
Hotel.create!(name: "The Holiday Inn", rating: BigDecimal.new('3.75'))

so that you stay well away from floating point front to back.