2013-07-16 30 views
0

我在模型用戶和評論之間建立了多對一關係。獲取一組用戶在發表最後評論前24小時發表的所有評論

我希望在每個用戶的最後評論(包括他/她最後的評論)之前24小時收集一組用戶所做的所有評論,最好是用散列表示。

這是我想出來的,但我不知道如何創建哈希值,只有從提到的時間跨度來評論。

Comment.order('updated_at desc').where(user_id: array_of_users_ids).group_by(&:user).each do |user, comments| 
    # rearrange the hash here? 
end 
+0

什麼數據庫您使用的? –

回答

1

對於這個SQL解決方案將是一個相關的子查詢,由非標準的日期算術取決於使用的RDBMS有點棘手。

你會尋找一個查詢,如:

select ... 
from comments 
where comments.user_id in (...) and 
     comments.updated_at >= (
     select max(updated_at) - interval '1 day' 
     from comments c2 
     where c2.user_id = comments.user_id) 

你應該能夠一起實現這一點:

Comment.where(user_id: array_of_users_ids). 
     where("comments.updated_at >= (
       select max(updated_at) - interval '1 day' 
       from comments c2 
       where c2.user_id = comments.user_id)"). 
     order(... etc