渲染的帖子既按时间倒序和total_votes [英] Render posts both by time desc and total_votes
本文介绍了渲染的帖子既按时间倒序和total_votes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想渲染饲料帖子首先对这个职位total_votes,如果没有票或者相同的票数,责令按时间倒序,意味着新的岗位会更高。我试图codeS是在这里。
I want to render posts in feed first by total_votes on this post, if no votes or same votes, ordered by time desc, means the new post will be higher. My attempting codes is here.
def feed
microposts = Micropost.where("created_at >= ? ", 30.minutes.ago).order('created_at desc')
end
<% if @feed_items.any? %>
<ol class="microposts">
<%= render @feed_items.sort_by { |post| post.total_votes }.reverse%>
</ol>
<%= will_paginate @feed_items %>
<% end %>
编辑:
edit:
我很遗憾,total_votes只是在我Micropost模型。
I am sorry that the total_votes is only a method in my Micropost Model.
Micropost型号
Micropost Model
class Micropost < ActiveRecord::Base
has_many :votes, as: :voteable
...
def total_votes
self.up_votes - self.down_votes
end
def up_votes
self.votes.where(vote: true).size
end
def down_votes
self.votes.where(vote: false).size
end
对不起再次.-。
Sorry again .-.
编辑2:
http://i.stack.imgur.com/Fgx3J.png
推荐答案
其他的答案是正确的,但只是为了好玩,你也可以对它进行排序的视图。
The other answers are right, but just for fun, you could also sort it in your view.
修改
@feed_items.sort_by { |post| post.total_votes }
要:
@feed_items.sort { |x,y| if x.total_votes < y.total_votes; 1 elsif x.total_votes == y.total_votes; y.created_at <=> x.created_at else; -1 end } %>
这篇关于渲染的帖子既按时间倒序和total_votes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文