3

我的模型中有这个:

  monetize :advance_amount_cents, allow_nil: true
  monetize :rental_amount_cents, allow_nil: true

我使用 AutoNumeric 来显示货币。它在参数中像这样将其发送回控制器:

'rental_amount' = "2050.12"

从模型返回此错误:

activerecord.errors.models.rental_period.attributes.rental_amount.invalid_currency

当我可以用逗号而不是点作为十进制发送货币时,它会接受货币。这里的最佳做法是什么?理想情况下,我希望所有被货币化的属性都可以接受任何作为小数分隔符、逗号或点的内容。这也是 Monetize 的做法:

pry(main)> Monetize.parse "2050.12"
=> #<Money fractional:205012 currency:USD>
pry(main)> Monetize.parse "2050,12"
=> #<Money fractional:205012 currency:USD>

这是完美的。如何配置我的模型(或一般的 Monetize gem)以接受两者作为参数(点或逗号)。

4

1 回答 1

1

希望这对某人有用。

模型:

monetize :rental_amount_cents, allow_nil: true

看法:

  = f.input :rental_amount, label: 'Rental amount' do
    .input-group
      = text_field_tag :rental_amount, @rental_period.rental_amount, class: 'form-control', id: "#{@rental_period.new_record? ? '' : (@rental_period.id.to_s + '_')}rental_amount_rate_rendered"
      = f.hidden_field :rental_amount, class: 'rate-input'
      %span.input-group-addon €

Javascript设置:

$('[id$=rate_rendered]').add('.flex-rate').autoNumeric('init', settings.money_nosign).on('keyup', function() {
  var $hid;
  $hid = $(this).parent().find('input.rate-input');
  if ($(this).autoNumeric('get') !== '') {
    return $hid.val($(this).autoNumeric('get').replace('.', ','));
  } else {
    return $hid.val(0);
  }
});

在我的设置中(仅相关部分:

window.settings = {
  money_nosign: {
    aDec: ',',
    aSep: '.',
    vMin: '-999999999.99'
  }
};
于 2020-05-29T09:29:33.510 回答