samvermette
samvermette

Reputation: 40437

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?

Upvotes: 14

Views: 11032

Answers (2)

user1492307
user1492307

Reputation: 41

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

Upvotes: 4

Reuben Mallaby
Reuben Mallaby

Reputation: 5767

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)

Upvotes: 12

Related Questions