I use money-rails
gem in my rails application.
I have model Transaction
.
class Transaction < ActiveRecord::Base
monetize :amount_money, as: :amount, with_model_currency: :currency, numericality: {greater_than_or_equal_to: 0}
end
And form for adding new transaction.
= simple_form_for [:post_manager, @transaction] do |f|
= f.label t('activerecord.attributes.transaction.amount')
= f.input :amount, class: 'form-control'
= f.submit t('views.transactions.submit.create'), class: 'btn btn-md btn-success'
In my controller action:
def create
@transaction = Transaction.new(transaction_params)
@transaction.save
respond_with(@transaction, location: post_manager_transactions_path)
end
In my money initializer:
MoneyRails.configure do |config|
config.register_currency = {
priority: 1,
iso_code: 'BYR',
name: 'Belarusian Ruble',
symbol: 'Br',
disambiguate_symbol: 'BYR',
subunit_to_unit: 1,
symbol_first: false,
decimal_mark: '.',
thousands_separator: ' ',
iso_numeric: '974',
smallest_denomination: 100
}
end
When I try to add new transaction:
In my controller action:
[1] pry(#<PostManager::TransactionsController>)> @transaction
=> #<Transaction:0x000001018ebfa0 id: nil, kind: "withdraw", amount_money: 12300, note: "vf", approved: nil, wallet_id: 1, category_id: 1, created_at: nil, updated_at: nil>
[2] pry(#<PostManager::TransactionsController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"hAHFdamHK7CI41zXiHUCSb+RUg+57JR9sZTIhi2frcLEQELakQuOvhs8xaWMwK32XbxTsTfplCQJA7XigsueLQ==",
"transaction"=>{"kind"=>"withdraw", "category_id"=>"1", "amount"=>"123", "note"=>"vf"},
"commit"=>"Создать операцию",
"controller"=>"post_manager/transactions",
"action"=>"create"}
So. In my params :amount is 123, but in my new transaction :amount is 12300, so i have 2 extra zeros in my amount money field.
And I really don't know how to fix it. Maybe someone have had such problem before?
This is the expected behaviour of the
money-rails
gem. It will save the currency amount in it's lowest denomination in order to prevent rounding errors.Since you have not specified the currency of the amount you're entering, it defaults to
USD
and converts it to cents, which is why you're seeing that result:$123 * 100 = 12300
The gem is smart enough to convert currency amounts into their lowest denomination. However, it needs to know the currency it is working with, since not all currencies behave the same.
The way you approach this is dependent on your application logic. However, as a test you could add the following hidden field to your form that would yield the result you expect.
= f.input :amount_currency, as: :hidden, input_html: { value: "BYR" }
L