Reputation:
I am creating some table data in a Rails-React application.
I had creating this piece of data here in console:
2.3.3 :024 > Crop.create date: Date.today, cropname: 'Radishes', ismetric: false, bagspackaged: '20', unitweight: '0.5', totalweight: '10'
Today I realized that Rails did not accept the 0.5 decimal for unitweight and no matter how I try to update it in console, it does not save.
This is my schema.rb file:
ActiveRecord::Schema.define(version: 20171004224716) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "crops", force: :cascade do |t|
t.date "date"
t.string "cropname"
t.boolean "ismetric"
t.integer "bagspackaged"
t.integer "unitweight"
t.integer "totalweight"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Upvotes: 2
Views: 2911
Reputation: 1132
Two issues here
First you have given the data type integer
to unitweight
and totalweight
, while you should have given it decimal
or float
in order to accept and store fractions. decimal
data type with precision is better as it will give you more accurate result as stated below in the comments' section.
when you use decimal
you can control it by The precision which is total number of digits in a number, whereas scale is number of digits following the decimal point.
here is an example
add_column :tickets, :price, :decimal, precision: 5, scale: 2
this will allow you to store decimal numbers like these 60.00, 80.99 and 100.00
Second you are passing string
to integer
, it is not a problem because rails will convert it to integer
as long as it is a valid integer
otherwise it will be 0
. But generally it is not a good practice.
Upvotes: 5
Reputation: 15393
I would avoid rolling back your crops table, it would just be more work. It is up to you.
I would just do:
rails g migration ChangeUnitweightToFloat
Inside that file I would configure like so:
class ChangeUnitweightToFloat < ActiveRecord::Migration
def change
change_column :crops, :unitweight, :float
end
end
With these two steps, you should be go to go. For future reference, please keep in mind that if you want to work with decimals, it will either be a t.decimal or t.float.
Upvotes: 4
Reputation: 7136
You could use a decimal
(or float
) type field instead of an integer:
create_table "crops", force: :cascade do |t|
t.decimal "unitweight"
end
and then don't use quotes around the value:
2.3.3 :024 > Crop.create date: Date.today, cropname: 'Radishes', ismetric: false, bagspackaged: '20', unitweight: 0.5, totalweight: '10'
Upvotes: 2
Reputation: 239240
That isn't a decimal, it's a string. Don't put quotes around your numeric literals.
Crop.create(
date: Date.today,
cropname: 'Radishes',
ismetric: false,
bagspackaged: 20,
unitweight: 0.5,
totalweight: 10
)
Upvotes: 1