Ruby on Rails Models. Why does a decimal{2,1} with scope 1 allow more than digit after the decimal point?

情到浓时终转凉″ 提交于 2019-12-10 12:22:47

问题


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.



来源:https://stackoverflow.com/questions/23200991/ruby-on-rails-models-why-does-a-decimal2-1-with-scope-1-allow-more-than-digit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!