9

I need to query all posts from a specific user and include all comments and the user who belongs to the comment.

class User < ...
  has_many :posts
  has_many :comments
end

class Post < ...
  belongs_to :user
  has_many :comments
end

class Comment < ...
  belongs_to :user
  belongs_to :post
end

@posts = current_user.posts.include(:comments)

Is is possible to also get the comment user? I list a lot of posts and comments. I do not want to query each comment user.

Thx / Tobias

sandelius
  • 507
  • 2
  • 6
  • 13

2 Answers2

27

Try

@posts = current_user.posts.includes( :comments => :user)

Read more about it here

rb512
  • 6,880
  • 3
  • 36
  • 55
cristian
  • 8,676
  • 3
  • 38
  • 44
  • 1
    Is it possible to limit the comment in this query. I only want the 5 latest comments to be included. If I loop shout.comments.limit(5) a new query is run – sandelius Dec 18 '11 at 21:33
  • 1
    In my answer: `Post has_many :comments, :include => [:user], :limit => 5` – clyfe Dec 18 '11 at 22:42
  • Yeah but I also wan't to fetch all comments on one page, or even paginate them? – sandelius Dec 19 '11 at 06:13
  • Anyone know how this has changed in Rails 4 and 5 ? I cannot find any information on how this has changed and I'm stuck on this, upgrading my app from 3.2 to 5.0 – Mathieu J. May 11 '16 at 13:13
  • Includes works the same in rails 4 and I think in 5 also – cristian Jun 23 '16 at 15:39
11

How about include at the relation definition statement?

:include
Specify second-order associations that should be eager loaded when this object is loaded.

class Post <
  belongs_to :user
  has_many :comments, :include => [:user], :limit => 5
end
clyfe
  • 23,695
  • 8
  • 85
  • 109
  • 1
    It looks like :include isn't a valid option (at least not with Rails 4.1), is there an alternative? – FeifanZ Oct 22 '14 at 15:14