Rails includes nested relations

2019-03-26 14:38发布

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

2条回答
叼着烟拽天下
2楼-- · 2019-03-26 15:31

Try

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

Read more about it here

查看更多
聊天终结者
3楼-- · 2019-03-26 15:37

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
查看更多
登录 后发表回答