Skip to content

Instantly share code, notes, and snippets.

@yosukehasumi
Created April 2, 2019 06:36
Show Gist options
  • Save yosukehasumi/32504ebe648035c58a4d7593e74a47f7 to your computer and use it in GitHub Desktop.
Save yosukehasumi/32504ebe648035c58a4d7593e74a47f7 to your computer and use it in GitHub Desktop.
Money Gem

Money Gem

Money displaying in cents has been driving me nuts, let's fix that since I promised a long time ago that we would!

Update table

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_amount

and add rename_column to the migration

class RenameTransactionAmount < ActiveRecord::Migration[5.2]
  def change
    rename_column :transactions, :amount, :amount_cents
  end
end

Update Gemfile

Add the 'Money' gem to the Gemfile

gem 'money-rails'

Configure Money

in config/initializers/money.rb add in our default currency

MoneyRails.configure do |config|
  config.default_currency = :cad
end

Apply monetize to Transaction amount

In app/models/transaction.rb we can add the :monetize rule to the amount_cents column by adding:

monetize :amount_cents

How it works

Now 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

Update views

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>

Update months view

in app/views/months/show.html.erb

replace

Total: $<%= @report.month_total * 0.01 %>

with

Total: <%= humanized_money_with_symbol @report.month_total %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment