Efficient counting of an association’s association
- by Matthew Robertson
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?