Gandalf StormCrow
Gandalf StormCrow

Reputation: 26192

Rails scope created within month

I've got some issues with writing my model scope. I want to filter my model objects based on a month in which they are published, i.e model BlogPost :

scope :published_in_month, ->(date) { where(published_date: date.at_beginning_of_month..date.at_end_of_month) }

So this is my controller method :

def list_by_month
    @date = Time.parse("#{params[:year]}/#{params[:month]}")
    puts "DATE IS #{@date}"
    @posts = BlogPost.published_in_month(@date).page(params[:page]).per(10)
    render :index
  end

So date printed out I see is :

DATE IS 2013-12-01 00:00:00 +0100

But in my log and it the page I see post(s) from wrong month, this is a entry log :

SELECT "blog_posts".* FROM "blog_posts" WHERE ("blog_posts"."published_date" BETWEEN '2013-11-30 23:00:00.000000' AND '2013-12-31 22:59:59.999999') LIMIT 10 OFFSET 0

Where is this 2013-11-30 coming from when my input date is 2013-12-01, and how can I rewrite my scope if I made mistake with it to produce incorrect query

Upvotes: 3

Views: 3108

Answers (2)

Marcelo Barreto
Marcelo Barreto

Reputation: 162

This could help:

scope :from_month, -> { where(created_at: DateTime.now.beginning_of_month..DateTime.now.end_of_month) }

Upvotes: 8

zwippie
zwippie

Reputation: 15515

Perhaps it is better to use SQL methods to determine the month of each record:

scope :published_in_month, ->(date) { where("MONTH(created_at) = ?", date.month) }

Postgresql version:

scope :published_in_month, ->(date) { where("DATE_PART('month', timestamp created_at) = ?", date.month) }

(not tested)

Upvotes: 3

Related Questions