这个特定的 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 %>
这将按赞成票的数量排序。