Home > Software engineering >  Count how many posts came out after the last post ActiveRecord
Count how many posts came out after the last post ActiveRecord

Time:05-20

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!

CodePudding user response:

def self.count_posts_last_white(last_post_id, last_white_id)
   self.where(id: last_white_id..last_result_id - 1).count
end

I asked the question a short time ago, but battling my mind I ended up finding a solution

CodePudding user response:

Maybe something like this:

def self.count_post_by_color(color)
  where(created_at: Post.where(color: color).last.created_at..Time.current).count
end
  • Related