How do I get Rails to eager load counts?

后端 未结 4 1777
悲&欢浪女
悲&欢浪女 2020-12-14 20:30

This is related to a question a year and change ago.

I put up an example of the question that should work out of the box, provided you have sqlite3 available: https:

4条回答
  •  天命终不由人
    2020-12-14 21:27

    As @apneadiving suggested, counter_cache works well because the counter column gets automatically updated when records are added or removed. So when you load the parent object, the count is included in the object without needing to access the other table.

    However, if for whatever reason you don't like that approach, you could do this:

    Post.find(:all,
              :select => "posts.*, count(comments.id) `comments_count`",
              :joins  => "left join comments on comments.post_id = posts.id")
    

提交回复
热议问题