仅显示上周创建的帖子 [英] show only posts created in last week

查看:76
本文介绍了仅显示上周创建的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够显示帖子,并按照几个条件对它们进行排序,首先是对他们的投票数,其次是根据其创建日期.我不希望显示超过一周的帖子,所以只显示最后一周的帖子.我尝试这样做:

I want to be able to show posts and have them sorted by a couple criteria, first by the amount of votes they have on them and second by the date at which they were created. I don't want posts that are more than a week old being displayed so only posts in the last week. I tried doing this:

 <%= render @posts.sort_by { |post| post.votes.count if post.created_at < 1.week.ago.utc }.reverse %>

但是它给了我一个比较NilClass和2个失败的错误

but it gave me an error of comparison of NilClass with 2 failed

我知道代码可以通过按投票数对帖子进行排序来工作,但是我也想限制时间,所以有人可以告诉我如何做到这一点.我还是新手,为简单起见.

I know the code works by just sorting posts by vote count but I also want to limit time so could someone tell me how this can be done. I'm still new so sorry for the simplicity.

推荐答案

@Salil的解决方案还可以,但是我建议添加counter_cache列( https://stackoverflow.com/a/11498634/1392074 )放入:

Solution by @Salil is ok, but I would suggest adding counter_cache column ( http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html ) and changing recent_post code (from this comment: https://stackoverflow.com/a/11498634/1392074 ) into:

def self.recent_posts
  Post.where("created_at >= ?", 1.week.ago.utc).order("votes_count DESC, created_at DESC")
end

这篇关于仅显示上周创建的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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