2017年8月23日 星期三

rails 效能 - group

```
app/controllers/posts_controller.rb
def report
-  @posts = Post.all.include(:user).sort_by{ |post| post.subscriptions.size }.reverse[0,10]
+  @posts = Post.includes(:user).joins(:subscriptions).group("posts.id").select("posts.*, COUNT(subscriptions.id) as subscriptions_count").order("subscriptions_count DESC").limit(10)
end
```

```
app/views/posts/report.html.erb
-  <td><%= post.subscriptions.size %></td>
+  <td><%= post.subscriptions_count %></td>
```

沒有留言:

張貼留言