将 Money 对象转换添加到 Rails 3.1 中的求和查询

发布于 2024-12-26 13:57:28 字数 828 浏览 1 评论 0原文

另一个菜鸟问题看起来应该很简单:

感谢这里收到的帮助,我可以轻松获得所选交易的总和:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静若繁花 2025-01-02 13:57:28

经过大量的抚摸和阅读,但最终弄清楚了以下内容:

trip_hash = bankroll.transactions.group_by(&:trip_id).map {|tr,t| Hash[tr, t.map(&:amount).inject(:+)]}

=>[{0=>#<Money cents:137693 currency:USD>}, {7=>#<Money cents:-39509 currency:USD>}, {10=>#<Money cents:50009 currency:USD>}]

地图中的地图做到了!哈希化使其易于查看,并且保留 Money 对象以用于格式化目的......

Took a lot of canoodling and reading, but finally figured out the following:

trip_hash = bankroll.transactions.group_by(&:trip_id).map {|tr,t| Hash[tr, t.map(&:amount).inject(:+)]}

=>[{0=>#<Money cents:137693 currency:USD>}, {7=>#<Money cents:-39509 currency:USD>}, {10=>#<Money cents:50009 currency:USD>}]

Map within the map did it! Hashifying makes it view friendly, and it retains the Money object for formatting purposes....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文