show only posts created in last week

…衆ロ難τιáo~ 提交于 2019-12-04 06:14:33
Maciej Litwiniuk

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

The code to find posts should be in Model and not on Views. There is always a good idea that you should fetch the records which we need to display instead fetching the records and showing some of it on views. You should do something like following

in your post.rb

def self.recent_posts
  Post.select("p.*, COUNT(v.id) AS count").where("post.created_at >= 1.week.ago.utc").joins("p LEFT JOIN votes v on p.id=v.post_id").order("count, created_at DESC")
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!