14

I know this can be done:

Article.where("published_at <= ?", Time.now).includes(:comments)

But what if I'd like to only get comments posted in the past month?

Does the .includes operator allow conditions?

samvermette
  • 40,269
  • 27
  • 112
  • 144

2 Answers2

12
Article.includes(:comments).where("articles.published_at <= ? and comments.created_at >= ?", Time.now, Time.now - 1.month)

EDIT:

Article.joins(:comments).where("articles.published_at <= ? and comments.created_at >= ?", Time.now, Time.now - 1.month)
Reuben Mallaby
  • 5,740
  • 4
  • 47
  • 45
  • Wow, didn't know I could do that. Thank you so much. – samvermette Feb 02 '11 at 22:39
  • 8
    Actually, this query only returns articles that *have* a comment posted in the past month. I need to have *all* the articles returned, along with each article's comments posted in the past month (if there's any). – samvermette Feb 03 '11 at 06:47
  • 8
    `joins` does an inner join. Same problem. `includes` does a left outer join, which is what we want, but the desired filter is applied on the where clause and not in the join. – Derek Prior Jan 25 '12 at 16:09
  • 1
    @Derek were you able to find a solution? – bfcoder Sep 10 '13 at 21:30
  • 1
    NOTE: here, **comments** is used as **relation name in the join**, and as **table name in the where**. If you defined `has_many comments, class_name: "Post"`, you would have written `Article.joins(:comments).where("... posts.created_at >= ?", Time.now - 1.month)` – cyrilchampier Oct 17 '13 at 13:20
  • @bfcoder this question might help: http://stackoverflow.com/questions/25099668/pgundefinedtable-error-missing-from-clause-entry-for-table-when-using-joins – koosa Jan 06 '15 at 04:09
4

In Rails4, it should be: Article.includes(:comments).where("articles.published_at <= ? and comments.created_at >= ?", Time.now, Time.now - 1.month).references(:comments)

Source

Berendschot
  • 3,026
  • 1
  • 21
  • 43