ruby-on-railsfilteringinner-joinactivemodelcounter-cache

Getting count of entries for a sub-model with date filtering in Rails


I want to get count of objects for a sub-model in Rails with date filtering.

Let's explain in detail:

Assume that I have two models.

Also the Comment model belongs to Post model

I want to get comments count for each post by date range. For example; I want to get only today's counts.

Does anyone have an idea that how can I do it without many DB queries? Is it possible with counter cache?


Solution

  • One single query

    date_start = params[:date_from].to_date.beginnig_of_day
    date_end = params[:date_end].to_date.end_of_day
    
    Post.includes(:comments)
          .where(comments: {created_at: date_start..date_end})
          .group(:id)
          .count