我在模型User和Comment之间有多对一的关系。
我想在每个用户的最后评论(包括他/她的最后评论)之前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