简体   繁体   English

Rails 4查询按月和年排序

[英]Rails 4 query sorting by month and year

I am having trouble with the best way to do this but essentially I have a blog where I want to show an archive of the month and year of all the published blogs. 我在最好的方法上遇到了麻烦,但实际上我有一个博客,我想在该博客中显示所有已发布博客的月份和年份的存档。 Clicking a link "May 2012" will bring you to all the blogs written in between that month on the same year (for example: May 5th 2012, May 20th 2012...). 单击链接“ 2012年5月”将带您到同年该月之间撰写的所有博客(例如:2012年5月5日,2012年5月20日...)。 Is there a way to get all the records within the same month of the same year just using created_at and passing params of the numerical month and year? 有没有一种方法可以只使用created_at并传递数字月份和年份的参数来获取同一年同一个月内的所有记录? Is there a better way to do this overall. 有没有更好的方法来整体上做到这一点。

Try something like this in your controller: 在您的控制器中尝试以下操作:

month = Date.new(params[:year], params[:month])
@entries = Blog.where(created_at: month.all_month)

The #all_month method will create a Range containing the beginning and end of the month, and passing a Range in the where clause makes a BETWEEN query for the date. #all_month方法将创建一个包含月份开始和结束的范围,并在where子句中传递范围,从而对日期进行BETWEEN查询。

Yes you can do that in Rails, eg for all blogs in May 2014: 是的,您可以在Rails中做到这一点,例如对于2014年5月的所有博客:

time = DateTime.new(2014,5)
blogs = Blog.where("created_at >= ? and created_at <= ? ", time.beginning_of_month, time.end_of_month)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM