acts_as_votable ordering by upvotes

前端 未结 1 1577
逝去的感伤
逝去的感伤 2021-02-09 17:23

I haven\'t been able to find anything that works so far for ordering questions by number of upvotes using the acts_as_votable gem.

Here are my upvote and index methods:<

相关标签:
1条回答
  • 2021-02-09 17:57

    This particular gem has a caching migration you can run as well.

    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 would be to create a new migration with the sample code and use that to sort against.

    Once you've created that migration, you can sort on one of those columns:

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

    For example:

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

    That will sort by the number of up votes.

    0 讨论(0)
提交回复
热议问题