Rails includes nested relations

巧了我就是萌 提交于 2019-12-21 04:09:08

问题


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


回答1:


Try

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

Read more about it here




回答2:


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


来源:https://stackoverflow.com/questions/8554498/rails-includes-nested-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!