I’m building a social networking application, users be able to have some posts and other users able to like and comments on those posts.
class Post < ActiveRecord::Base belongs_to :user has_many :likes has_many :comments end class Comment < ActiveRecord::Base belongs :user belongs :post, counter_cache: true end class Like < ActiveRecord::Base belongs :user belongs :post, counter_cache: true end class PostSerializer < ActiveModel::Serializer attributes :id, :body, :likes_count, :comments_count, is_liked def likes_count object.likes.size # should pull from counter_cache end def comments_count object.comments.size # should pull from counter_cache end # did current_user already like this post def is_liked object.likes(user_id: scope.id).exists? # N+1 end end
Another way to prevent N+1 this issue is to use
Post.recent.includes(:likes, :comments), but I think there is still a problem with scaling because it has to load likes and comments and we are not interested much on detail of those associations at all.
Do you to have any suggestion solution? Or other ways to modeling this problem?