Rails includes nested relations

后端 未结 2 651
南笙
南笙 2021-02-15 03:54

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         


        
相关标签:
2条回答
  • 2021-02-15 04:31

    Try

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

    Read more about it here

    0 讨论(0)
  • 2021-02-15 04:45

    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
    
    0 讨论(0)
提交回复
热议问题