ruby-on-railsmoney-rails

Money-Rails Gem with Rails 4 - Instance Currencies


Im trying to use monetise in my Rails 4 app (with money-rails gem).

How do you allow a user to submit a number dollars only? When I input 100 I get $1 instead of $100.

In my model, I have:

monetize :participation_cost_pennies, with_model_currency: :participation_cost_currency

I am using instance currencies, so users select the relevant currency. My table has columns for participation cost, participation cost pennies and participation cost currency.

In my form, I have:

   <%= par.select :participation_cost_currency,
                             options_for_select(major_currencies(Money::Currency.table)),
                             label: false,
                             prompt: "Select your costs currency" %>

            <%= par.input :participation_cost, label: false, placeholder: 'Whole numbers only', :input_html => {:style => 'width: 250px; margin-top: 20px', class: 'response-project'} %>

In my view, I have:

   <%= money_without_cents_and_with_symbol @project.scope.participant.participation_cost  %>

By replacing 'participation cost pennies' with participation cost in the form, I get the number to show as a whole number without cents I now get $10,000 when i enter 100 (so the reverse problem in that it is adding 2 00s to the end of my input.


Solution

  • Seems, you use price column inside the database and ask users to input exactly same input. This two different setters/getters. Try the following:

    # add migration
    rename_column :products, :price, :price_cents
    
    
    # set monetize for this field inside the model
    class Product
      monetize :price_cents
    end
    
    # inside form use .price instead of .price_cents method
    f.text_field :price
    

    In this case user set price in dollars and it will be automatically converted to the cents to store it inside price_cents field.