Search code examples
ruby-on-railsruby-on-rails-3sortingdatevote

Sort posts by number of votes within certain time frame


I currently have a voting system implemented in my app and I'm sorting the posts by number of votes with this code in my view:

  <%= render @posts.sort_by { |post| post.votes.count }.reverse %> 

I want to sort by number of votes for each post by also don't want the post to be any more than lets say 5 days old. How can I sort the posts by both number of votes and date simultaneously.


Solution

  • I figured out another way to do it although I appreciate your help it may not be the cleanest way but I did

       def most
         range = "created_at #{(7.days.ago.utc...Time.now.utc).to_s(:db)}"
         @posts = Post.all(:conditions => range)
         @title = "All Posts"
         @vote = Vote.new(params[:vote])
    
         respond_to do |format|
           format.html
           format.json { render :json => @users }
         end
       end 
    

    for my controller

    created a route of /most :to => 'posts#most'

    and made a view with the original code I had in my view.

    I know its not the best way but I am still new to coding so its the best way I could figure out how.