Rails范围在月内创建 [英] Rails scope created within month

查看:105
本文介绍了Rails范围在月内创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写我的模型范围时遇到了一些问题。我想根据发布的月份过滤我的模型对象,即模型BlogPost:

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

所以这是我的控制器方法:

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

所以打印日期我看到的是:

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

但是在我的日志和页面中,我看到错误的月份的帖子,这是一个条目日志:

  SELECTblog_posts* FROMblog_postsWHERE(blog_posts。published_dateBETWEEN'2013-11-30 23:00:00.000000 'AND'2013-12-31 22:59:59.999999')LIM IT 10 OFFSET 0 

这个 2013-11-30 来自我的输入日期是 2013-12-01 ,如果我错误地使用它来产生错误的查询,我如何重写我的范围

解决方案

也许最好使用SQL方法来确定每个记录的月份:

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

Postgresql版本:

 范围:published_in_month, >(date){where(DATE_PART('month',timestamp created_at)=?,date.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

解决方案

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)

这篇关于Rails范围在月内创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆