I am trying to use the value from a has_many :through relationship to retrieve a list of Authors but my logic is failing.
What would be the best way to achieve this
Currently trying this without success
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)
I can retrieve just the books by using
Book.where("date(release_date) BETWEEN ? AND ?", start_date, end_date)
But want to get this query above working
Your query is likely failing because you are using
includeswith a SQL string fragment. Rails does not infer any associations onincludesusing SQL strings, so references must be used in conjunction:Alternatively, you can use the query DSL to construct the same where clause and Rails will be able to infer the association:
If you're just trying to filter down to a list of
authors and don't need thebooks at all, I'd recommend a subquery: