1

I'm building a Rails application that allows a user to catalogue tires by inputting values into the UI. When I created the tire class , I made it as

class CreateArticles < ActiveRecord::Migration[5.0]
  def change
    create_table :tires do |t|
      t.decimal :price
      ...
  end
end

When I ran the program I realized that I'd neglected to specify the precision and scale of the decimal attribute. This resulted in the program being unable to accept non-integer values and displaying all values appended by .0 Because I was so much farther along on the program, I decided to write another migration to just change price to a float by writing the following migration:

class ChangeTiresToFloat < ActiveRecord::Migration[5.0]
  def change
    change_column :tires, :price, :float
   end

After running db:migrate, there is no change in the behavior of the program. Should this not have made it so that the UI could accept float values?

Edit: Before resorting to making the price column a float value, I did try to fix the decimal value by adding the missing attributes with this migration:

class MoneyDecimalFix < ActiveRecord::Migration[5.0]
  def change
    change_column :tires, :price, :decimal, :precision => 8, :scale => 2
  end
end

After rolling forward the migration, the program's behavior still did not change.

Mr_CATnDOG
  • 11
  • 3
  • 1
    Don't use floats for prices. http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – max Jan 09 '17 at 02:22
  • 1
    Agree with @max you can use a money library like https://github.com/RubyMoney/money-rails – Hass Jan 09 '17 at 06:45
  • Although I am planning to switch to the Money library on an optimization update after this, I'd first like to know what my error is in implementing the migration. Why it is that rolling it forward results in no change to the program's behavior. – Mr_CATnDOG Jan 09 '17 at 17:44

1 Answers1

0

Although it is possible to use a change_column migration to edit the price value to include the decimal attribute's specifications, because the create_table is a reversible migration, it is advisable to instead roll the migration back and manually implement the change to ultimately read

t.decimal :price, :precision => 8, :scale => 2

then roll the migration forward again.

It is however worth noting that, although having the price column correctly defined in the migration is an essential step, it alone did not fix the issue of the form not accepting decimal values.

The error was ultimately in my Views. Within Rails, the number_field tag, on its own, will not accept decimal values, it must be 'combined' with a text_field tag in order to do so as such:

<%= f.number_field :price, class: :text_field, step: :any %>

Mr_CATnDOG
  • 11
  • 3