will_paginate 和 named_scopes [英] will_paginate with named_scopes
问题描述
我正在使用 will_paginate 进行分页,到目前为止,它一直运行良好,除了这一件事.
I'm using will_paginate for pagination, which has been working well so far, except for this one thing.
例如,如果我尝试对范围进行分页
If I try to paginate a scope, for instance
class User < ActiveRecord::Base
named_scope :scope, lambda { etc }
end
User.scope.paginate({:page => params[:page], :per_page => 10})
这会告诉我 paginate 是一个未定义的方法.我宁愿不必仅针对此范围使用第二个解决方案,我可以在这里做些什么吗?
That will tell me paginate is an undefined method. I'd rather not have to use a second solution for only this scope, is there something I can do here?
推荐答案
低增益,klew 的版本应该是开箱即用的.在你的版本中你应该写:
Lowgain, klew's version should work out of the box. In your version you should write:
User.scope.paginate :page => params[:page], :per_page => 10
我更喜欢另一种分页方法.它允许使控制器更干净并在模型级别封装分页,例如:
I prefer another approach to pagination. It allows to make controller more clean and encapsulates pagination at model level, for e.g.:
class Property < ActiveRecord::Base
named_scope :all_properties, lambda {{ :order => "name asc" }}
def self.admin_properties(page = 1)
self.all_properties.paginate(:page => page, :per_page => Settings.admin.per_page)
end
end
在控制器中非常清晰的代码:
And in a controller pretty clear code:
class Admin::PropertiesController < Admin::AdminController
def index
@properties = Property.admin_properties(params[:page])
end
end
ps:Settings.admin.per_page - 这是 Searchlogic 设置.
p.s: Settings.admin.per_page - this is Searchlogic settings.
这篇关于will_paginate 和 named_scopes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!