1

我在我的 Rails 应用程序中使用money-railsgem。我有模型Transaction

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 个额外的零。

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

4

1 回答 1

0

这是money-railsgem 的预期行为。它将以最低面额保存货币金额,以防止舍入错误。

由于您没有指定输入金额的货币,因此默认USD为美分并将其转换为美分,这就是您看到该结果的原因:

$123 * 100 = 12300

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

您处理此问题的方式取决于您的应用程序逻辑。但是,作为测试,您可以将以下隐藏字段添加到您的表单中,这将产生您期望的结果。

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

大号

于 2016-07-10T23:06:30.190 回答