show only posts created in last week

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.

Answers


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

Need Your Help

How to create an object in my case?

javascript jquery object

I want to create an object like the following

How do I clip an image in xaml and limit the image width? (Winrt)

c# .net xaml windows-runtime

I have an image that can get set through an api, I want the image to get clipped when it's wider than 250 px. And that works. However, the image is in a stackpanel along with some textblocks. An...