show only posts created in last week

2020-07-11 10:14发布

问题:

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 %>

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.

回答1:

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


回答2:

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