Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 ActiveRecord conditional includes?

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?

like image 656
samvermette Avatar asked Feb 02 '11 15:02

samvermette


2 Answers

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)
like image 163
Reuben Mallaby Avatar answered Oct 17 '22 03:10

Reuben Mallaby


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

like image 42
user1492307 Avatar answered Oct 17 '22 02:10

user1492307