我的模型中有这个:
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)以接受params(点或逗号)。
答案 0 :(得分: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'
}
};