首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对货币对象执行数学运算--“未知方法”(Exchange_to)表示0:fixnum [Rails 4] [Money Gem]

对货币对象执行数学运算--“未知方法”(Exchange_to)表示0:fixnum [Rails 4] [Money Gem]
EN

Stack Overflow用户
提问于 2014-06-03 11:48:07
回答 1查看 1.1K关注 0票数 2

目前,我已经通过money-rails安装了money gem,它运行得很好。我有一个名为:default_price:default_price_cents的货币化对象,并且正在使用:currency列来定义货币。我还有一个:default_packs列,它是一个用户定义的整数,它是货币化的,包模型每天用一个:date列和一个:amount列存储一个新条目。

这是我的user.rb

代码语言:javascript
复制
  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时,问题就出现了。

如果您需要更多的信息,请告诉我,我们非常感谢您的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-03 12:10:15

我没有用过这个宝石,但看起来你并没有按照read的方式来寻找money-rails的创业板

https://github.com/RubyMoney/money-rails

假设您在模型:default_price_cents中有一个字段,您可以.

代码语言:javascript
复制
  monetize :default_price_cents, with_model_currency: :currency

..。这将自动给出一个名为“:default_price`”的货币化字段。你不需要定义它,也不需要将它“货币化”,它已经是一个货币属性。

类似地,您应该创建名为daily_saving_potential_centstotal_saving_potential_centstotal_money_spent_cents等的方法。您将自动拥有一个方法daily_saving_potentialtotal_saving_potential等等。

在方法中,使用raw (.._cents)属性进行计算。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24014409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档