Rails 指定预加载关联的条件

Rails Specifying Conditions on Eager Loaded Associations

我有用户和待办事项模型,用户有很多待办事项,待办事项属于用户,我需要找到在最后一天创建待办事项的用户,如果有则给他们发邮件。我试过 guide 的查询,但它没有 return 任何记录,即使有因为(我认为)日期格式:

User.includes(:todos).where(todos: { created_at: 1.day.ago})

我也试过:

User.includes(:todos).where(todos: { created_at: 1.day.ago.to_date})

User.includes(:todos).where(todos: { "date(created_at) = ?", 1.day.ago.to_date})

但最后一个不起作用: SyntaxError: unexpected '}', expecting end-of-input

我用的是Postgres,created_at是一个日期时间字段(默认rails时间戳)

在 Psql 中:

created_at | timestamp without time zone | not null

根据 post 中的规范,您需要获取过去一天创建的待办事项,因此

下面提到的查询将不起作用

User.includes(:todos).where(todos: { created_at: 1.day.ago.to_date})

因为 1.day.ago 给出了特定的时间戳,数据库搜索相同的时间戳,即包括匹配的小时、分钟和秒。

所以更好的方法是搜索涵盖一整天的时间戳,从而提供范围是最好的选择。

修改查询如下:

User.includes(:todos).references(:todos).where("todos.created_at >= ? and todos.created_at <= ?", 1.day.ago.beginning_of_day, 1.day.ago.end_of_day)

这将获取过去一天创建的涵盖全天时间的待办事项。