将 Money 对象转换添加到 Rails 3.1 中的求和查询
另一个菜鸟问题看起来应该很简单:
感谢这里收到的帮助,我可以轻松获得所选交易的总和:
@trip_hash = transactions.sum(:amount_cents, :group => :trip_id)
但是,问题是 :amount_cents 列代表一个原始 Money 对象,需要在之前进行转换求和以适应货币兑换。 “由”过程组成的资金看起来像这样:
composed_of :amount,
:class_name => "Money",
:mapping => [%w(amount_cents cents), %w(currency currency_as_string)],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
我可以轻松调用:
transactions.map(&:amount).inject(:+)
获得转换后的总计,但我不知道如何在分组的上下文中执行此操作。
再次非常感谢您的帮助!
Another noob question that seems like it should be simple:
Thanks to the help received here, I can easily get a sum of selected transactions:
@trip_hash = transactions.sum(:amount_cents, :group => :trip_id)
The issue, however, is that the :amount_cents column represents a raw Money object that needs to be transformed before summing in order to accommodate currency exchange. The Money "composed of" Procs look like this:
composed_of :amount,
:class_name => "Money",
:mapping => [%w(amount_cents cents), %w(currency currency_as_string)],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
I can easily call:
transactions.map(&:amount).inject(:+)
to get a transformed grand total, but I can't figure out how to do it in the context of the groupings.
Many thanks, again, for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过大量的抚摸和阅读,但最终弄清楚了以下内容:
地图中的地图做到了!哈希化使其易于查看,并且保留 Money 对象以用于格式化目的......
Took a lot of canoodling and reading, but finally figured out the following:
Map within the map did it! Hashifying makes it view friendly, and it retains the Money object for formatting purposes....