Message
具有属性location
、like_count
、vote_count
。
和Comment
belongs_to :message
,并具有属性like_count
,vote_count
我已经设法弄清楚如何计算location
以及Message
在该特定location
中获得的票数。
@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
我可以保持这样,那就没问题了,但是如果我能找到一种方法来将comments
的vote_count
和like_count
与user_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
也许如果我location
也分配给Comments
会更容易?
让我知道您的想法,任何建议将不胜感激!
我不确定如何在单个查询中执行此操作,但是通过两个查询和一点普通的 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')
第一个查询将messages
表和comments
表中的所有like_count
和vote_count
添加到具有关联comments
messages
。使用left_outer_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')
第二个查询仅将messages
表中的所有like_count
和vote_count
添加到没有关联comments
messages
。
totals = with_comments.dup
totals.each_key do |location|
totals[location] += without_comments[location].to_i
end
dup
第一个哈希并迭代它,将两个哈希的值相加并将nil
值转换为0
。
您可以执行此查询。
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
对于活动记录:
@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")
我希望这对你有帮助。
您可以转到此链接以获取详细信息 http://sqlfiddle.com/#!9/65bb32/6。