Rails包含嵌套关系

san*_*ius 9 activerecord relationship ruby-on-rails-3

我需要查询来自特定用户的所有帖子,并包括所有评论和属于评论的用户.

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)
Run Code Online (Sandbox Code Playgroud)

是否也可以获得评论用户?我列出了很多帖子和评论.我不想查询每个评论用户.

Thx/Tobias

cri*_*ian 26

尝试

@posts = current_user.posts.includes( :comments => :user)
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多相关信息


cly*_*yfe 10

包含在关系定义语句中怎么样?

:include
指定加载此对象时应该急切加载的二阶关联.

class Post <
  belongs_to :user
  has_many :comments, :include => [:user], :limit => 5
end
Run Code Online (Sandbox Code Playgroud)