【问题标题】:Allowing both comma or dot in currency parameter允许在货币参数中使用逗号或点
【发布时间】:2017-10-15 12:13:32
【问题描述】:

我的模型中有这个:

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

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

'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)以接受两者作为参数(点或逗号)。

【问题讨论】:

  • 你找到解决这个问题的办法了吗?
  • @DmitryPolushkin 刚刚查看了代码,这对我有用(添加了答案)。

标签: ruby-on-rails money-rails


【解决方案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'
  }
};

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多