2011-12-18 86 views
8

我需要查詢來自特定用戶的所有帖子,幷包含所有評論和屬於評論的用戶。Rails包含嵌套關係

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) 

也可以得到評論用戶嗎?我列出了很多帖子和評論。我不想查詢每個評論用戶。

THX /托比亞斯

回答

26

嘗試

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

瞭解更多關於它here

+1

是否可以限制在此查詢中的評論。我只想要包含5條最新評論。如果我循環shout.comments.limit(5)一個新的查詢運行 – sandelius 2011-12-18 21:33:34

+1

在我的答案:'後has_many:評論,:包括=> [:用戶],:限制=> 5' – clyfe 2011-12-18 22:42:20

+0

是的,但我也不想在一個頁面上獲取所有評論,甚至分頁? – sandelius 2011-12-19 06:13:01

10

關於如何包括的關係定義語句?

:include
指定加載此對象時應急切加載的二階關聯。

class Post < 
    belongs_to :user 
    has_many :comments, :include => [:user], :limit => 5 
end 
+1

它看起來像:include不是一個有效的選項(至少不是Rails 4.1),還有其他選擇嗎? – FeifanZ 2014-10-22 15:14:48

+0

@FeifanZ它應該是'includes'。那應該很好 – ahnbizcad 2014-10-23 03:18:45