Money-Rails Gem with Rails 4 - Instance Currencies

你离开我真会死。 提交于 2019-12-06 05:52:43

问题


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.


回答1:


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.




回答2:


In the money-rails gem the prices are saved in cents, so it's normal that 100 outputs $1, since it is indeed 100 cents. $100 would be 10000. This is made on purpose, to avoid floating point rounding errors.

You can write a helper function to convert your input to cents, if you want to deal with dollars in your app.




回答3:


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


来源:https://stackoverflow.com/questions/30587638/money-rails-gem-with-rails-4-instance-currencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!