目前,我已经通过money-rails安装了money gem,它运行得很好。我有一个名为:default_price和:default_price_cents的货币化对象,并且正在使用:currency列来定义货币。我还有一个:default_packs列,它是一个用户定义的整数,它是货币化的,包模型每天用一个: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对来自my模型的:amount字段的所有条目进行求和。问题是,当我认为调用total_savings时,我在说total_savings时会出错。
有趣的是,如果在:default_price_cents中使用:default_price而不是在daily_saving_potential中使用:default_price,那么就不会得到错误,但是模型中自定义的字段显示的是默认货币,而不是用户定义的货币,而default_price字段则显示用户定义的正确货币。也许这个问题与我的包模型中的货币对象与非货币对象相乘的事实有关?无论如何,当我从total_money_spent中减去total_saving_potential时,问题就出现了。
如果您需要更多的信息,请告诉我,我们非常感谢您的帮助!
发布于 2014-06-03 12:10:15
我没有用过这个宝石,但看起来你并没有按照read的方式来寻找money-rails的创业板
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)属性进行计算。
https://stackoverflow.com/questions/24014409
复制相似问题