2011-02-02 20 views

答えて

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

EDIT:Rails4で

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

うわー、私はそれを行うことができます知りませんでした。どうもありがとうございます。 – samvermette

+8

実際には、このクエリは、過去1か月に投稿されたコメントを持つ記事のみを返します。先月に掲載された各記事のコメントとともに、*すべての*記事を返す必要があります(もしあれば)。 – samvermette

+0

インクルードの代わりにジョインはどうですか? (編集を参照) –

4

、それは次のようになります。 Article.includes(:comments).where("articles.published_at <= ? and comments.created_at >= ?", Time.now, Time.now - 1.month).references(:comments)

Source

+0

'includes'は関連付け名前は 'references'が実際のテーブル名を必要とします。 –

+1

'.references()'トリックが保存されました... – 7urkm3n

関連する問題