使用Active Record Reputation System gem,当我按投票排序时,不会发生排序

在信誉系统gem的RailsCast之后,我将以下代码添加到microposts_controller中

def index @microposts = Micropost.paginate(page: params[:page]).find_with_reputation(:votes, :all, order: "votes desc") @micropost = current_user.microposts.build end 

但除了我在模型中设置的默认范围外,我的索引操作中没有排序

在我的微博模型中,我有

 class Micropost  { order('created_at DESC') } 

如果我将默认范围更改为

 default_scope -> { order('votes DESC') } 

它的工作方式只适用于索引页面,但会破坏我的所有其他页面。

我尝试删除默认范围并留在find_with_reputation方法中,但它仍然没有通过投票排序。

我也尝试在像这样的微博模型中的方法中定义范围

  def self.popular find_with_reputation(:votes, :all, {:order => 'votes desc'}) end 

并像这样在microposts_controller中创建代码

  def index @microposts = Micropost.paginate(page: params[:page]).popular @micropost = current_user.microposts.build end 

它仍然没有按投票排序。

以下是访问微博索引页面的日志输出的副本https://gist.github.com/anonymous/9745552

这是gem的链接https://github.com/NARKOZ/activerecord-reputation-system/tree/rails4

我的routes.rb用于微博看起来像这样

  resources :microposts, only: [:create, :destroy, :index] do member { post :vote } member { post :retweet} end 

任何指导表示赞赏。

更新

我的主页设计的设计与我为Micropost Index Feed所做的设计不同。 也许比较哪些有效,哪些无效有助于查明问题。

我有一个静态页面控制器,它设置这样的主动作的范围

 def home @micropost = current_user.microposts.build @feed_items = current_user.feed.paginate(page: params[:page]) end 

在用户模型中,我定义静态页面控制器中使用的feed方法,如此

 def feed Micropost.from_users_followed_by_including_replies(self) end 

from_users_followed_by_including_replies(self)方法是我在微博模型中设置的范围

 scope :from_users_followed_by_including_replies, lambda { |user| followed_by_including_replies(user) } def self.followed_by_including_replies(user) followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id) where("user_id IN (#{followed_ids}) OR user_id = :user_id OR to_id = :user_id", { :user_id => user }) end 

也许我需要对Microposts控制器的Index动作采用类似的方法

编辑

在获取代码时,我发现真正的问题源于使用default_scope

即使在添加自己的order()时,仍会应用默认范围中指定的原始order()子句。

作为旁注,这个问题在Rails 4.0中得到修复,但行为在4.0.1中得到了恢复。

解决方案是应用reorder()

 # model def self.popular reorder('votes desc').find_with_reputation(:votes, :all) end # controller def index @microposts = Micropost.page(params[:page]).popular end 

原始答案

似乎直接使用paginate方法可能无法与activerecord-reputation-system

但是,我发现一些示例显示您可以使用will_paginate pageper方法:

也许它会像这样工作:

 Micropost.page(params[:page]).per(30).find_with_reputation(:votes, :all, order: "votes desc") 

或者像这样的模型范围:

 def self.popular find_with_reputation(:votes, :all, order: 'votes desc') end 

你可以这样做:

 Micropost.page(params[:page]).per(30).popular 

另外,作为旁注,当只需要一个member块时,你的路径文件有点奇怪。 我会让它看起来像这样:

 resources :microposts, only: [:create, :destroy, :index] do member do post :vote post :retweet end end