How to get last month records in postgreSQL

postgresql, ruby-on-rails

Solution

You can have a scope in the model defined as:

scope :in_last_month, where('created_at BETWEEN ? AND ? ', 1.month.ago.beginning_of_month , 1.month.ago.end_of_month)

Or

scope :in_last_month, where(:created_at => 1.month.ago.beginning_of_month..1.month.ago.end_of_month)

Then call:

 Model.in_last_month

similarly you may have scopes for current month, before previous month etc.

Problem

How to get last month records in postgreSQL ? Please help. Most probably how can I write the psql query for this? Note: I have a `created_at` field in my table.

Original source