Ruby on rails 分组时如何对父记录和子记录求和?

Ruby on rails 分组时如何对父记录和子记录求和?,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,消息具有属性位置,如计数,投票计数 而评论属于:message,并具有属性,如@user.id和特定的@message.location对评论的投票数和喜欢数进行求和,我会非常喜欢它 使之成为: # => "Total votes and likes of your Messages and Comments posted in New York, United States ": 192 # => "Total votes and likes of your Messages an

消息
具有属性
位置
如计数
投票计数

评论
属于:message
,并具有
属性,如
投票数

我已经设法弄清楚了如何将
位置
以及在该特定
位置
中给出的
消息
的票数进行散列

@votes_by_place = Message.where(
:user_id => @user.id).select(
:location).group(:location).sum('like_count + vote_count')

# => "Total votes and likes of your Messages posted in New York, United States ": 192
# => "Total votes and likes of your Messages posted in Paris, France ": 93
我可以这样保存它,这很好,但如果我能找到一种方法,用
用户id=>@user.id
和特定的
@message.location
评论的
投票数
喜欢数
进行求和,我会非常喜欢它

使之成为:

# => "Total votes and likes of your Messages and Comments posted in New York, United States ": 192
# => "Total votes and likes of your Messages and Comments posted in Paris, France ": 93
如果我也将
位置
分配给
注释
可能会更容易些

让我知道你的想法和任何建议将不胜感激

您可以执行此查询

SELECT location, SUM(comments.vote_count + comments.like_count) as total_vote_and_like FROM messages
JOIN comments ON messages.id = comments.message_id
GROUP BY messages.location
对于ActiveRecord:

@votes_by_place = Message.select("messages.location, SUM(comments.vote_count + comments.like_count) as total_vote_and_like")joins(:comments).where(user_id => @user.id).group("messages.location")
我希望这对你有帮助


您可以转到此链接以获取详细信息。

我不知道如何在一个查询中完成此操作,但使用两个查询和一个简单的Ruby就可以完成。也许其他人能找到更有效的方法

with_comments = Message.where(user_id: @user.id).
  left_outer_joins(:comments).
  group(:location).
  sum('messages.like_count + messages.vote_count + comments.like_count + comments.vote_count')
第一个查询添加了
消息
注释
表中具有关联
注释的
消息
的所有
s和
投票计数
s。使用
left\u outer\u joins
可确保对
group
的调用为所有消息位置(包括那些没有相关注释的位置)添加哈希键,从而表示所有用户的消息位置

without_comments = Message.where(user_id: @user.id).
  left_outer_joins(:comments).
  where(comments: { message_id: nil }).
  group(:location).
  sum('messages.like_count + messages.vote_count')
第二个查询仅从
消息
表中为没有相关
注释的
消息
添加所有
s和
投票计数
s

totals = with_comments.dup

totals.each_key do |location|
  totals[location] += without_comments[location].to_i
end

dup
第一个散列并对其进行迭代,将两个散列的值相加,然后将
nil
值转换为
0

我想我是通过使用连接(:注释)来实现的。但是,当我试图在视图中输出它时,它只打印
#
否。。这将汇总具有相同@user.id.的所有注释。。不是每条
消息中的注释。我看到了位置。我忘了添加连接(:注释)。我终于成功地实现了这一点。不管是否有更好的方法,这是目前正确的答案。这涵盖了所有方面,如果有一条没有注释的消息,以及所有注释,无论它是否属于特定消息。万分感谢!很高兴有帮助@克拉什托