Efficient counting of an association’s association

Posted by Matthew Robertson on Stack Overflow See other posts from Stack Overflow or by Matthew Robertson
Published on 2013-11-09T03:12:17Z Indexed on 2013/11/09 3:53 UTC
Read the original article Hit count: 557

In my app, when a User makes a Comment in a Post, Notifications are generated that marks that comment as unread.

class Notification < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
  belongs_to :comment

class User < ActiveRecord::Base
  has_many :notifications

class Post < ActiveRecord::Base
  has_many :notifications

I’m making an index page that lists all the posts for a user and the notification count for each post for just that user.

# posts controller
@posts = Post.where(
    :user_id => current_user.id
  )
  .includes(:notifications)

# posts view
@posts.each do |post|
  <%= post.notifications.count %>

This doesn’t work because it counts notifications for all users. What’s an efficient way to do this without running a separate query for each post?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord