渲染的帖子既按时间倒序和total_votes帖子、间倒序、total_votes

2023-09-11 23:11:30 作者:习惯那些不曾习惯的习惯゜

我想渲染饲料帖子首先对这个职位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:

https://m.xsw88.com/allimgs/daicuo/20230911/4403.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 } %>