Search code examples
ruby-on-railsrubyactiverecord

Count how many posts came out after the last post ActiveRecord


I have the following question in ActiveRecord.

Model and Example Fields

Post [ title:string content:string color:string ]

Imagine that my model receives recurring posts, but sometimes a specific post comes with a "white" color.

Now imagine that a post with the color "white" came out about 30 minutes ago, and several posts came out with other colors in those 30 minutes.

The problem is that I can't imagine how to count how many posts came out after the last post with white color!


Solution

  • While both of the proposed solutions will work they require instantiating a Post object which is unnecessary in my opinion instead we can make this a single query like so

    class Post < ApplicationRecord 
    
      scope :posts_since, ->(color) {
             where(arel_table[:created_at].gt(
                      select(arel_table[:created_at].maximum).where(color: color).arel))}
    end 
    

    Callable as

    Post.posts_since(:white) 
    

    Resulting Query

    SELECT 
      posts.* 
    FROM 
      posts 
    WHERE
      created_at > (SELECT MAX(posts.created_at) FROM posts WHERE posts.color = 'white'))
    

    To "count" you can just add count e.g. Post.posts_since(:white).count