Rails 3 ActiveRecord条件包括?

时间:2011-02-02 15:39:55

标签: ruby-on-rails ruby-on-rails-3 activerecord

我知道可以做到这一点:

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

但如果我只想在过去一个月发表评论怎么办?

.includes运算符是否允许条件?

2 个答案:

答案 0 :(得分:13)

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

编辑:

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

答案 1 :(得分:4)

在Rails4中,它应该是: Article.includes(:comments).where("articles.published_at <= ? and comments.created_at >= ?", Time.now, Time.now - 1.month).references(:comments)

Source