0

I have a many-to-one relationship between the models User and Comment.

I would like to collect, preferably in a hash, all comments made by a set of users the 24 hours prior to each user's last comment (including his/her last comment).

This is what I have come up with, but I dont know how to create the hash with comments only from the time span mentioned.

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

1 回答 1

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
于 2013-07-16T13:04:09.793 回答