How to extract highest voted model instances in acts_as_votable?
ruby, ruby-on-rails
Solution
I realize that this is an old question, nonetheless I ran into the same issue and felt like leaving here my solution. Thus, the way I accomplished that was by running the migration below, as the documentation describes.
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
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
Then in my model I added the class method below
class Post
def self.highest_voted
self.order("cached_votes_score DESC")
end
end
Afterwards, `Post.highest_voted` will return the highest voted posts.
In order to return just 30 posts, you can do something like `Post.highest_voted.limit(30)`
Problem
Let's say that I have a post model that is under the acts acts_as_votable plugin. How can I take the top 30 posts with the highest vote counts? It should be pretty simple; however, I cannot locate any documentation within the plugin that elaborates on this.