2额外的零钱货币栏杆

2额外的零钱货币栏杆

问题描述:

我在我的rails应用程序中使用money-rails宝石。我有型号Transaction2额外的零钱货币栏杆

class Transaction < ActiveRecord::Base 
    monetize :amount_money, as: :amount, with_model_currency: :currency, numericality: {greater_than_or_equal_to: 0} 
end 

用于添加新事务的表单。

= 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' 

在我的控制器动作:

def create 
    @transaction = Transaction.new(transaction_params) 
    @transaction.save 

    respond_with(@transaction, location: post_manager_transactions_path) 
end 

在我的钱初始化:

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 

当我尝试添加新的交易:

在我的控制器动作:

[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"} 

所以。在我的参数中:金额是123,但是在我的新交易中:金额是12300,所以我在金额货币字段中有2个额外的零。

我真的不知道如何解决它。也许有人以前有过这样的问题?

+1

我相信这两个零是kopejki =) – 2014-11-25 12:16:10

+0

@МалъСкрылевъ,不,这不是kopejki :) – 2014-11-25 12:21:03

+1

钱宝石做它的计算中美分。他们声称这个策略的问题较少。 Такчтоэтовсетакикопейки:)'表示货币值为整数,单位为美分。这可以避免浮点舍入错误 – 2014-11-25 14:20:06

这是宝石money-rails的预期行为。它会将货币金额保存在最低面额中以防止舍入错误。

既然你没有指定你在输入金额的货币,则默认为USD并将其转换为美分,这就是为什么你看到的是结果:

$123 * 100 = 12300

宝石足够聪明,可以将货币金额转换为最低的面值。但是,它需要知道它所使用的货币,因为并非所有货币的行为都相同。

你接近这个的方式取决于你的应用程序逻辑。但是,作为测试,您可以将以下隐藏字段添加到您的表单中,以获得您期望的结果。

= f.input :amount_currency, as: :hidden, input_html: { value: "BYR" }

大号