我目前通过money-rails
安装了金钱宝石,它工作得很好。我有一个名为:default_price
和:default_price_cents
的货币化对象,并使用:currency
列来定义货币。我还有一个:default_packs
列,这是一个用户定义的可货币化的整数,还有一个Pack模型,它每天存储一个带有:date
列和:amount
列的新条目。
这是我的user.rb
has_many :packs
register_currency :usd
monetize :default_price_cents, with_model_currency: :currency
monetize :default_price, with_model_currency: :currency
monetize :daily_saving_potential, with_model_currency: :currency
monetize :total_saving_potential, with_model_currency: :currency
monetize :total_money_spent, with_model_currency: :currency
monetize :total_savings, with_model_currency: :currency
def daily_saving_potential
return default_price * default_packs
end
def total_saving_potential
days = self.packs.count
return days * daily_saving_potential
end
def total_money_spent
amount = self.packs.map(&:amount).sum
return amount
end
def total_savings
return total_saving_potential - total_money_spent
end
total_money_spent
对Pack模型中:amount字段的所有条目求和。问题是,当total_savings
在我的视图中被调用时,我得到一个错误说 Unknown Method "exchange_to" for 0:fixnum
。
有趣的是,如果我在daily_saving_potential
中使用:default_price_cents
而不是:default_price
,那么我不会得到错误,但是我在模型中自定义的字段显示默认货币而不是用户定义的货币,而default_price
字段显示用户定义的正确货币。也许这个问题与我将货币对象与Pack模型中的非货币对象相乘的事实有关?无论如何,当我从total_saving_potential
中减去total_money_spent
时,问题就出现了
如果你需要更多的信息,请告诉我,所有的帮助都是非常感激的!
我没有使用过这个gem,但是看起来您并没有遵循read-me for money-rails gem
https://github.com/RubyMoney/money-rails假设您在模型:default_price_cents
中有一个字段,您可以…
monetize :default_price_cents, with_model_currency: :currency
…这将自动给你一个货币化的字段':default_price '。你不需要定义它,也不需要"货币化"它,它已经是一个金钱属性了。
同样,你应该创建名为daily_saving_potential_cents
、total_saving_potential_cents
和total_money_spent_cents
等方法。您将自动拥有daily_saving_potential
和total_saving_potential
等方法。
在你的方法计算中使用raw (.._cents)属性