Rails包含嵌套关系 [英] Rails includes nested relations
本文介绍了Rails包含嵌套关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要查询所有文章从一个特定的用户,包括所有的意见和谁属于注释的用户。
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 /托比亚斯
推荐答案
尝试
@posts = current_user.posts.includes( :comments => :user)
了解更多关于它<一个href="http://guides.rubyonrails.org/active_record_querying.html#eager-loading-multiple-associations">here
这篇关于Rails包含嵌套关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文