Money displaying in cents has been driving me nuts, let's fix that since I promised a long time ago that we would!
We need to rename the column name from amount to amount_cents so that we can properly use the 'Money' gem. So let's create a migration
bin/rails generate migration rename_transaction_amountand add rename_column to the migration
class RenameTransactionAmount < ActiveRecord::Migration[5.2]
def change
rename_column :transactions, :amount, :amount_cents
end
endAdd the 'Money' gem to the Gemfile
gem 'money-rails'in config/initializers/money.rb add in our default currency
MoneyRails.configure do |config|
config.default_currency = :cad
endIn app/models/transaction.rb we can add the :monetize rule to the amount_cents column by adding:
monetize :amount_centsNow if you'd like to see the amount in cents we can still call Transaction.first.amount_cents
But now if you'd like to parse that amount into a proper 'money' object you can try Transaction.first.amount
Even better the 'money' gem comes with some handy methods built in that allow us to use humanized_money_with_symbol in our views
For more info checkout https://github.com/RubyMoney/money-rails
in app/views/transactions/_form.html.erb let's update the form to use our new amount column:
Replace
<%= f.number_field :amount, { class: 'form-control' } %>with
<%= f.number_field :amount, { step: 0.01, class: 'form-control' } %>in app/views/transactions/show.html.erb
replace
Amount: <strong><%= @transaction.dollar_amount %></strong>with
Amount: <strong><%= humanized_money_with_symbol(@transaction.amount) %></strong>in app/views/months/show.html.erb
replace
Total: $<%= @report.month_total * 0.01 %>
with
Total: <%= humanized_money_with_symbol @report.month_total %>