Mel
Mel

Reputation: 2685

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.

Upvotes: 4

Views: 1344

Answers (3)

p4sh4
p4sh4

Reputation: 3291

In the money-rails gem, prices are saved in cents, so a price of 10 will be saved as 1000 price_cents. This is made on purpose to avoid floating point rounding errors.

To display the right price(without the cents), just call the price method on your object and it will display the correct non-cents price

Upvotes: 1

aratak
aratak

Reputation: 364

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.

Upvotes: 3

Pardeep Dhingra
Pardeep Dhingra

Reputation: 3946

Assuming you have price_cents column in your table. You can try this code to convert dollar amount to cents before monitize:

monetize :price_cents
before_save :dollars_to_cents

def dollars_to_cents
    #convert dollar to cents
    self.price_cents = self.price_cents * 100 
end

Upvotes: 1

Related Questions