将will_paginate与named_scoped一起使用

时间:2009-09-18 17:45:19

标签: ruby-on-rails

在使用分页和命名范围时,我遇到了问题。 使用named_scope的第二页或任何连续的分页页面仍返回第一页的结果。 使用find(:all)可以正确返回分页结果。 有没有人能够正确使用它们或遇到同样的问题?

class Study < ActiveRecord::Base
  named_scope :opened, :conditions => {:study_stat => [205, 11203]}
end

#find(:all) returns correct studies for both pages
Study.find(:all, :conditions => {:study_stat => [205, 11203]}).paginate(:per_page => 10,  :page => 1).each {|e| pp e.study_number  }
Study.find(:all, :conditions => {:study_stat => [205, 11203]}).paginate(:per_page => 10,  :page => 2).each {|e| pp e.study_number  }

#using named_scope returns correct result for the first page but the second page has the same studies as ones in the page one.
Study.opened.paginate(:per_page => 10,  :page => 1).each {|e| pp e.study_number  }
Study.opened.paginate(:per_page => 10,  :page => 2).each {|e| pp e.study_number  }

2 个答案:

答案 0 :(得分:1)

我发现了原因。如rdoc中所述 ,:order参数是使分页正常工作所必需的。对于named_scope尤其如此。 (我使用SQL Server 2005)

User.active.paginate(:all, :per_page => 5,  :page => 1, :order=>'id').each {|e| pp e.user_name  }

User.active.paginate(:all, :per_page => 5,  :page => 2, :order=>'id').each {|e| pp e.user_name  }

答案 1 :(得分:0)

尝试在对named_scope的paginate调用中包含:all选项。我记得前一段时间遇到过类似的问题,并为我解决了这个问题。

所以,而不是

Study.opened.paginate(:per_page => 10, :page => 2)

Study.opened.paginate(:all, :per_page => 10, :page => 2)