Rails eager loading of counts?

后端 未结 5 1015
暖寄归人
暖寄归人 2021-02-02 14:50

Eager loading is nice with the include attribute

Post.find(:all, :include => :author)

I\'m wondering if you can also eager load counts, like

5条回答
  •  别那么骄傲
    2021-02-02 15:23

    Building off of avaynshtok's answer, the following technique should just make 2 database calls.

    # ./app/controllers/posts_controller.rb
    
    def index
      # First load the posts
      @posts = Post.all
    
      # Then you can load a hash of author counts grouped by post_id
      # Rails 4 version:
      @comment_counts = Comment.group(:post_id).count
      # Rails 3 version:
      # @comment_counts = Comment.count(:group => :post_id)
    end
    

    Then in your view

    
    
    <% @posts.each do |post| %>
      
      post_count: <%= @comment_counts[post.id] %>
    <% end %>
    

提交回复
热议问题