通过投票订购微博

时间:2011-04-30 08:03:33

标签: ruby-on-rails-3 sqlite

我无法弄清楚如何格式化代码。我在这里(以更好的方式)重新提出这个问题:http://railsforum.com/viewtopic.php?id=43839

拥有一个具有投票功能的简单微博网站。我希望能够通过votes.size显示发布的微博。我似乎无法让它工作,并希望得到一些指导。

模型:

class Micropost
  attr_accessible :content
  has_many :votes 
  belongs_to :user 
  default_scope :order => 'microposts.created_at DESC'


class Vote
  belongs_to :micropost

视图:

# microposts page
<% unless @picture.microposts.empty? %>
  <table class="microposts" summary="User microposts">
    <%= render @microposts %>
  </table>
<% end %>

# microposts partial
<tr>
  <td class="micropost">   
    <span class="gravatar">     
      <%= link_to gravatar_for(micropost.user, :size => '60'), micropost.user %>
    </span>
    <span class="content" >
      <%= micropost.content %>
    </span>
    <span id="vote_total_<%= micropost.id %>" class="micropost_votes">
      votes:<%= micropost.votes.size %>
    </span>
  <% if current_page?(root_path) && signed_in? %>
    <span id="vote_button">
      <%= button_to 'vote', micropost_votes_path(:micropost_id => micropost),
          :remote => true 
      %>
    </span>
  <% end %>  
  </td>
</tr>

控制器:

# VotesController
def create
  @micropost = Micropost.find(params[:micropost_id])
  @vote      = @micropost.votes.build params[:micropost_id]

  respond_to do |format|
    if @vote.save
      format.html { redirect_to @micropost }
      format.js        
    else
      format.html { redirect_to root }
    end
  end
end

我已经能够通过created_at日期对微博进行排序,但我似乎无法通过micropost.votes.size对微博进行排序。它似乎与根据不同模型的状态对一个模型进行排序有关。

2 个答案:

答案 0 :(得分:1)

Micropost.all(:select => "#{Micropost.table_name}.*, COUNT(#{Vote.table_name}.id) number_of_votes",
         :joins => :votes,
         :order => "number_of_votes desc")

答案 1 :(得分:0)

嗯,这是我找到的最好的解决方案。在渲染微博的视图中,我补充道:

.sort_by { |micropost| micropost.votes.size }

所以实际的渲染代码如下所示:

<%= render @microposts.sort_by { |micropost| micropost.votes.size } %>

我实际上撤消了我的帖子,以便投票总数最高的帖子位居首位。这很简单:

<%= render @microposts.sort_by { |micropost| micropost.votes.size }.reverse %>

我不知道这是否会造成数据库性能问题,但似乎运行良好。

相关问题