6

acts_as_votableこれまでのところ、 gemを使用して賛成票の数で質問を並べ替えるために機能するものを見つけることができませんでした。

これが私の賛成票とインデックスの方法です:

 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 %>

これを機能させるには、ビューとコントローラーに何を入れる必要がありますか?

4

1 に答える 1

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 %>

これは、賛成票の数でソートされます。

于 2013-09-30T21:20:59.553 に答える