Ruby on Rails:从对象数组创建求和数组
我有一个如下所示的对象数组:
[#<Holding id: 5, user_id: 21, outcome_id: 7, quantity: 200, cost_basis: nil, created_at: "2011-12-15 20:52:05", updated_at: "2011-12-15 20:52:05">,
#<Holding id: 6, user_id: 21, outcome_id: 7, quantity: 750, cost_basis: nil, created_at: "2011-12-15 21:31:30", updated_at: "2011-12-15 21:31:30">,
#<Holding id: 7, user_id: 21, outcome_id: 9, quantity: 1231, cost_basis: nil, created_at: "2011-12-15 21:35:31", updated_at: "2011-12-15 21:35:31">]
我通过使用模型的 find_all_by_user_id (Holding.find_all_by_user_id(21)) 检索了它。然而,我需要的是一系列总和。因此,举例来说,在这种情况下我想要得到的是:
[#<Holding id: 5, user_id: 21, outcome_id: 7, quantity: 950, cost_basis: nil, created_at: "2011-12-15 20:52:05", updated_at: "2011-12-15 20:52:05">,
#<Holding id: 7, user_id: 21, outcome_id: 9, quantity: 1231, cost_basis: nil, created_at: "2011-12-15 21:35:31", updated_at: "2011-12-15 21:35:31">]
如果我可以从我的 Outcomes 模型中提取 Outcome.description 并将其与 id 一起放入第二个数组中,那么效果会更好。我是否只需要循环并在outcome_id 匹配的地方创建总和,还是有更好的方法?
I have an array of objects that looks like this:
[#<Holding id: 5, user_id: 21, outcome_id: 7, quantity: 200, cost_basis: nil, created_at: "2011-12-15 20:52:05", updated_at: "2011-12-15 20:52:05">,
#<Holding id: 6, user_id: 21, outcome_id: 7, quantity: 750, cost_basis: nil, created_at: "2011-12-15 21:31:30", updated_at: "2011-12-15 21:31:30">,
#<Holding id: 7, user_id: 21, outcome_id: 9, quantity: 1231, cost_basis: nil, created_at: "2011-12-15 21:35:31", updated_at: "2011-12-15 21:35:31">]
I retrieved this by using my model's find_all_by_user_id (Holding.find_all_by_user_id(21)). What I need, however, is an array of sums. So, for instance, what I'd like to get instead in this instance is:
[#<Holding id: 5, user_id: 21, outcome_id: 7, quantity: 950, cost_basis: nil, created_at: "2011-12-15 20:52:05", updated_at: "2011-12-15 20:52:05">,
#<Holding id: 7, user_id: 21, outcome_id: 9, quantity: 1231, cost_basis: nil, created_at: "2011-12-15 21:35:31", updated_at: "2011-12-15 21:35:31">]
What would make it even better is if I could pull from my Outcomes model the Outcome.description and have it in this second array along with the id. Do I just have to loop over and create sums where outcome_id's match or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我会在 SQL 中执行此操作 -
SUM(quantity)
和GROUP BY Outcome_id
。如果你想在 Ruby 中使用它,你可以做
sums
现在是一个哈希,键是所有的outcome_ids,值是总数。请注意,在两种解决方案(SQL 和 Ruby)中,您都将丢失其他字段(holding_id、user_id、cost_basis、timestamps)中的信息,这可能不是您想要的。
Personally, I would do this in SQL -
SUM(quantity)
andGROUP BY outcome_id
.If you want it in Ruby, you can do
sums
is now a hash with key being all the outcome_ids and the value being the total quantity.Please note that in both solutions (SQL and Ruby) you will lose the information in the other fields (holding_id, user_id, cost_basis, timestamps), which may not be what you want.