2013-09-30 38 views
6

我一直未能找到任何工作到目前爲止通過使用acts_as_votable gem upvotes的數量排序問題。acts_as_votable upvotes排序

這裏是我給予好評和索引方法:

def upvote 
    @question = Question.find params[:id] 
    @question.liked_by current_user 
    redirect_to comment_questions_path 
end 

def index 
@comment = Comment.find params[:comment_id] 
@questions = @comment.questions 
end 

和我的問題查看:

<%= div_for(question) do %> 
<% if question.votes.size > 0 %> 
<div class="verifiedanswer"> 
<%= question.body %> 
</div> 

<% else %> 
<div class="answercontainer2"> 
<%= question.body %> 
</div> 
<% end %> 

我應該把視圖和控制器,使這項工作?

回答

11

這個特殊的gem有一個可以運行的緩存遷移。

https://github.com/ryanto/acts_as_votable#caching

class AddCachedVotesToPosts < ActiveRecord::Migration 
    def self.up 
    add_column :posts, :cached_votes_total, :integer, :default => 0 
    add_column :posts, :cached_votes_score, :integer, :default => 0 
    add_column :posts, :cached_votes_up, :integer, :default => 0 
    add_column :posts, :cached_votes_down, :integer, :default => 0 
    add_index :posts, :cached_votes_total 
    add_index :posts, :cached_votes_score 
    add_index :posts, :cached_votes_up 
    add_index :posts, :cached_votes_down 

    # Uncomment this line to force caching of existing votes 
    # Post.find_each(&:update_cached_votes) 
    end 

    def self.down 
    remove_column :posts, :cached_votes_total 
    remove_column :posts, :cached_votes_score 
    remove_column :posts, :cached_votes_up 
    remove_column :posts, :cached_votes_down 
    end 
end 

我的建議是要創建示例代碼新的遷移並用它來進行排序對。

一旦你創建了遷移,您可以排序這些列中的一種:

http://guides.rubyonrails.org/active_record_querying.html#ordering

例如:

<% Post.order(:cached_votes_up).each do |post| %> 
    ... html goodness here ... 
<% end %> 

將由最高票數排序。

+0

對不起,新的鐵軌,不知道我怎麼實現這個在我看來。 – user2759575

+0

增加了一點。 HTH –

+0

太棒了,謝謝。 – user2759575