Act_as_votable ordering by upvotes

I have not been able to find anything that still works to sort questions by the number of upvotes with acts_as_votable gem .

Here are my upvote and index methods:

  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 

and my questions:

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

What should I put in the view and controller to make this work?

+6
source share
1 answer

This particular stone has a cache migration that you can also trigger.

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 

My suggestion was to create a new migration with sample code and use it to sort.

Once you have created this migration, you can sort it by one of the following columns:

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

For instance:

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

This will sort by the number of votes.

+11
source

Source: https://habr.com/ru/post/954977/


All Articles