Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails includes nested relations

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

like image 778
sandelius Avatar asked Dec 18 '11 20:12

sandelius


2 Answers

Try

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

Read more about it here

like image 183
cristian Avatar answered Oct 16 '22 04:10

cristian


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
like image 36
clyfe Avatar answered Oct 16 '22 06:10

clyfe