根据Rails中最受欢迎的帖子对帖子进行排序

时间:2016-12-22 11:28:18

标签: ruby-on-rails ruby acts-as-votable

我正在尝试使用两个标签,一个用于最新帖子,另一个用于最喜欢的帖子。但是,我真的很困惑如何让我的帖子按最喜欢的(投票)排序。我确实使用acts_as_votable gem将投票系统部分放入网站。我是Rails的新手,请告诉我你需要提供哪些更多细节,谢谢。

1 个答案:

答案 0 :(得分:0)

您应该启用Caching。每次投票后,这些列将自动更新。

创建新迁移rails g migration add_cached_votes_to_posts并添加以下代码:

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_column :posts, :cached_weighted_score, :integer, :default => 0
    add_column :posts, :cached_weighted_total, :integer, :default => 0
    add_column :posts, :cached_weighted_average, :float, :default => 0.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
    add_index  :posts, :cached_weighted_score
    add_index  :posts, :cached_weighted_total
    add_index  :posts, :cached_weighted_average

    # 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
    remove_column :posts, :cached_weighted_score
    remove_column :posts, :cached_weighted_total
    remove_column :posts, :cached_weighted_average
  end
end

运行迁移命令rake db:migrate

使用缓存列进行排序:

Post.order(cached_votes_score: :desc)