0

I'm trying to get the money-rails gem working, and I'm having problems...

Other similar stackoverflow questions are 6 years old.

Here's the product I have the appropriate columns on:

class Transactions < ActiveRecord::Base
  belongs_to :user, optional: true
  validates :trans_id, uniqueness: true

  monetize :price_cents

end

I've got the gem in my Gemfile, and have run bundle install successfully.

When I create a new item and look at it with pry,

create(vendor:"foo",amount:2.6,trans_id:'123cccc')
 id: nil,
 vendor: "foo",
 amount_cents: 260,
 amount_currency: "USD",
 trans_id: "123cccc",
 tax_cents: 150,
 total_cents:410,
  1. How do I work with it in dollar amounts? I.e. I want to add amount_cents to tax_cents for total_cents. amount 2.60 instead of amount_cents: 260,
  2. Do I need to add a 'composed_of'?
  3. Also, why is 'cent's in the naming? I thought it was supposed to be removed as the vague documentation states:

In this case the name of the money attribute is created automagically by removing the _cents suffix from the column name.

jeancode
  • 5,856
  • 5
  • 12
  • 20
  • The money gem works with cents internally. These are stored in attributes with a `_cents` suffix. The gem then creates accessor methods (getters and setters) without the `_cents` suffix (hence "removing"). For example: `amount`, `tax` and `total`. See [method conversion](https://github.com/RubyMoney/money-rails#method-conversion) for an example. – Stefan Feb 12 '18 at 09:58

1 Answers1

0
  1. Cents issue

The money gem is storing the the amount in cents and in the table definition, 2 fields will define the property.

For e.g., consider having the property amount in Transaction. In schema.rb you will find 2 fields: amount_cents and amount_currency.

So, now you will have a transaction.amount with a money object in it. With money object you can:

  • use humanized_money @money_object from money_rails helpers to display the amount formatted
  • you can do operations, like addition, subtraction, even conversion to other currency

3) 'automagically attribute'

Having a migration:

class AddAmountToClient < ActiveRecord::Migration
  def change
    add_monetize :clients, :amount
  end
end

After the migration you can find in schema.rb

create_table "clients", force: :cascade do |t|
  t.integer  "amount_cents", limit: 8, default: 0,     null: false
  t.string   "amount_currency", default: "USD", null: false
end

What it's saying with attribute is created automagically by removing the _cents, it means that you can access amount property from the Client class with client.amount having a money object.

mmsilviu
  • 1,211
  • 15
  • 25