2

I just realized my column type needs to be decimal instead of integer

Can i make the change directly in my seeds.rb or there's something else i should do?

Also how do i do this if i intend to add a letter after the decimal?

Example: 2.0L, 2.5L, 5.7L, etc.

Maxxx
  • 363
  • 1
  • 6
  • 15
  • Does this answer your question? [Change database column type to decimal](https://stackoverflow.com/questions/21699047/change-database-column-type-to-decimal) – Rajdeep Singh Feb 29 '20 at 10:09
  • It's still unclear to me but then i have made changes to the question so kindly read again. – Maxxx Feb 29 '20 at 10:43
  • Is the letter always "L"? I'm guessing this is L for liter? Can it sometimes be different such as "ml"? If it's always "L" there's no real reason to keep it in the DB. If it can change I'd recommend a second field called "unit_of_measure". Or better yet convert the value of your field to a standard unit of measure and possibly name the field accordingly (`displacement_liters`) now you know the number is always in liters. If you want to store less than a liter it would be `0.75` for 750ml. – Dan Feb 29 '20 at 14:50

2 Answers2

6

If you want to store a letter in your DB, that column type can't be a decimal or integer. A string field would be more appropriate for your case. I'll assume your main question is regarding decimals though.

If you do want to change a column type in the DB, you're supposed to do it using Migrations. From terminal, in your app directory, run: bin/rails g migration changeFieldNameFromIntegerToDecimal.

This will generate a migration file with a timestamp in the filename, in which there is a change method telling rails how you want to change the database. In that change method, put:

def change
  change_column :table_name, :column_name, :decimal, precision: :8, scale: :2
end

the precision and scale options do the follwing (from the above link):

precision: Defines the precision for the decimal fields, representing the total number of digits in the number.

scale: Defines the scale for the decimal fields, representing the number of digits after the decimal point.

If you want to convert it to a string, then the migration file would contain:

def change
  change_column :table_name, :column_name, :string
end

Finally run bin/rails db:migrate from the terminal in your app directory to execute the migration.

Community
  • 1
  • 1
Mark
  • 6,112
  • 4
  • 21
  • 46
  • Thanks but then i guess changing to string instead of decimal seems to be the best option? – Maxxx Feb 29 '20 at 12:43
0

This will change the column type to decimal. To know about the scale and precision check out this Stackoverflow question https://stackoverflow.com/a/2377176/12297707 or the docs https://edgeguides.rubyonrails.org/active_record_migrations.html#column-modifiers

change_column :table_name, :column_name, :decimal, :precision => 8, :scale => 2, :default => 0
Dan
  • 1,238
  • 2
  • 17
  • 32
Naveed
  • 64
  • 4