Select Records Created within the Last X Months in Ruby on Rails

Suppose we have a blog application, and we want to show on the index page only the latest posts. Say we want to show the posts created within the last three months. How can we do that? We can use the Active Record query interface. We can use range conditions.

A Range is a Ruby class that represents an interval. We can use such an interval to select the posts between a specific time range. In our controller index method, we can select these posts like this:

@posts = Post.where(created_at: (Time.now - 3.months)..Time.now)

Time.now creates a new instance of time, and months is a method on the ActiveSupport::Duration object that applies on Numeric. The months method returns a duration. In our case, this duration is three months.

Post last updated on Feb 2, 2022