Money-Rails Gem with Rails 4 - 实例货币

Money-Rails Gem with Rails 4 - Instance Currencies

我正在尝试在我的 Rails 4 应用程序中使用货币化(使用金钱-rails gem)。

你如何让一个用户只提交一个数字美元?当我输入 100 时,我得到 1 美元而不是 100 美元。

在我的模型中,我有:

monetize :participation_cost_pennies, with_model_currency: :participation_cost_currency

我使用的是实例货币,所以用户 select 相关货币。我的 table 有参与成本、参与成本便士和参与成本货币的列。

在我的表格中,我有:

   <%= 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'} %>

在我看来,我有:

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

通过将表格中的 'participation cost pennies' 替换为参与费用,我得到的数字显示为一个没有美分的整数 我现在输入 100 时得到 10,000 美元(所以相反的问题是它加 2 00s 到我输入的结尾。

money-rails gem 中保存价格 in cents, so it's normal that 100 outputs , since it is indeed 100 cents. 0 would be 10000. This is made on purpose, to avoid floating point rounding errors

如果您想在您的应用中处理美元,您可以编写一个辅助函数将您的输入转换为美分。

假设您的 table 中有 price_cents 列。 您可以尝试使用此代码在 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

似乎,您在数据库中使用 price 列并要求用户输入完全相同的输入。这两个不同setters/getters。请尝试以下操作:

# 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

在这种情况下,用户以美元设置价格,它会自动转换为美分以存储在 price_cents 字段中。