ruby-on-railsmoney-rails

Allowing both comma or dot in currency parameter


I have this in my model:

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

I use AutoNumeric to display the currency. It sends it back to the controller like this in params:

'rental_amount' = "2050.12"

Which returns this error from the model:

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

It accepts the currency when I can get it to be sent with a comma instead of a dot as decimal. What is the best practise here? Ideally I would like for all attributes that are monetized to accept anything as decimal separator, comma or dot. That's also how Monetize seems to do it:

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

Which is perfect. How can I configure my model (or the Monetize gem in general) to accept both as params (dot or comma).


Solution

  • Hopefully this is of use to someone.

    Model:

    monetize :rental_amount_cents, allow_nil: true
    

    View:

      = 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 setup:

    $('[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);
      }
    });
    

    In settings I have (only relevant part:

    window.settings = {
      money_nosign: {
        aDec: ',',
        aSep: '.',
        vMin: '-999999999.99'
      }
    };