有很多使用日期的查询

问题描述 投票:0回答:1

我正在尝试使用 has_many :through 关系中的值来检索作者列表,但我的逻辑失败了。

实现这一目标的最佳方法是什么

目前尝试这个没有成功

start_date = '01/01/0001'.to_date.beginning_of_day
end_date = '01/01/2020'.to_date.end_of_day

Author.includes(:books).where("date(books.release_date) BETWEEN ? AND ?", start_date, end_date)

我可以通过使用只检索书籍

Book.where("date(release_date) BETWEEN ? AND ?", start_date, end_date)

但是想让这个查询正常工作

ruby-on-rails activerecord where-clause to-date
1个回答
1
投票

您的查询可能会失败,因为您正在使用

includes
和 SQL 字符串片段。 Rails 不会使用 SQL 字符串推断
includes
上的任何关联,因此 references 必须结合使用:

Author.includes(:books).references(:books).where("date(books.release_date) BETWEEN ? AND ?", start_date, end_date)

或者,您可以使用查询 DSL 构造相同的 where 子句,Rails 将能够推断关联:

Author.includes(:books).where({ books: { release_date: 1.year.ago..Time.now } })

如果您只是想过滤到

author
的列表并且根本不需要
book
,我建议使用子查询:

author_ids = Book.where("date(release_date) BETWEEN ? AND ?", start_date, end_date).select(:author_id)
Author.where(id: author_ids)
© www.soinside.com 2019 - 2024. All rights reserved.