2017-08-09 41 views
1

A Message具有location,like_count,vote_count的屬性。如何分組父母和孩子的記錄?

而且一個Commentbelongs_to :message並具有屬性like_countvote_count

我設法弄清楚如何得票Message在那個特定的location給予數一起湊出來的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 

我可以把它這樣,它會被罰款,但我真的很喜歡它,如果我能找到一種方法與user_id => @user.id和特定@message.location總結的commentsvote_countlike_count

所以它會變成:

# => "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 

也許,如果我分配給locationComments以及它會更容易?

讓我知道你的想法和任何建議將不勝感激!

回答

1

我不知道如何在單個查詢中做到這一點,但有兩個查詢和一個簡單的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') 

這第一個查詢添加所有like_count S和vote_count期從既爲messagesmessagescomments表具有關聯comments。使用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') 

這第二個查詢添加所有like_count S和vote_count期從只有messagesmessages沒有相關comments

totals = with_comments.dup 

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

dup第一哈希和遍歷它,加起來兩個散列值和轉換nil0

+0

我終於設法讓這個工作。無論是否有更好的方法來做到這一點,現在就是正確的答案。這包括所有方面,如果有一條消息沒有評論,並且所有評論,無論它是否屬於特定的消息。萬分感謝! – Crashtor

+0

很高興幫助! @Crashtor –

1

您可以執行此查詢。

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") 

我希望這會幫助你。

您可以轉到該鏈接獲取詳細信息http://sqlfiddle.com/#!9/65bb32/6

+0

嘿。非常感謝你做的這些。但是,'comments'缺少FROM-clause ... – Crashtor

+0

我想我通過使用連接(:評論),但我試圖在視圖中輸出它,它只打印'#<消息:0x007fd3a41c8fc0>' – Crashtor

+0

沒有..這總結了所有的評論相同的@ user.id ..不是在每個'message.location'中的註釋我看到 – Crashtor