将 will_paginate 移至模型
在我的问题模型上,我有一些范围
scope :recent, order("created_at DESC")
scope :approved, where("status = ?", "approved")
scope :answered, approved.recent.where("answers_count > ?", 0)
在我的问题控制器上,我正在使用范围
示例1检索问题:
@questions = Question.approved.recent
示例2:
@questions = User.find(session[:user_id]).topics.map { |t| t.questions.approved.recent }.flatten.uniq
我试图将will_paginate放在我的模型上,以使控制器上的事情变得更容易,但第二个示例非常棘手因为它使用映射根据偏好来检索问题。
我尝试将其添加到我的模型上
def self.pagination(page = 1)
self.paginate(:page => page, :per_page => 5)
end
,然后在我的控制器上添加
@questions = Question.approved.recent.pagination.(params[:page])
这对于第一个示例来说效果很好,但我不知道如何在第二个示例上实现它
有任何提示吗?
On my Question model I have some scopes
scope :recent, order("created_at DESC")
scope :approved, where("status = ?", "approved")
scope :answered, approved.recent.where("answers_count > ?", 0)
On my question controller I'm retrieving questions using the scopes
example 1:
@questions = Question.approved.recent
example 2:
@questions = User.find(session[:user_id]).topics.map { |t| t.questions.approved.recent }.flatten.uniq
I'm trying to put will_paginate on my model to make things easier on the controller but the 2nd example is very tricky as it is using mapping to retrieve questions according to preferences.
I've tried to add this on my model
def self.pagination(page = 1)
self.paginate(:page => page, :per_page => 5)
end
and then on my controller I have
@questions = Question.approved.recent.pagination.(params[:page])
That works fine for the 1st example but I Dont know how to implement that on the 2nd example
Any hints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来像 Rails 3。请务必使用
~>; will_paginate gem 的 3.0.pre2
版本。您可以在作用域链的末尾使用
paginate
方法。例如,您的“示例 1”将是:我看到您创建了一个自定义方法 (
pagination
) 来包装此模式,但最好暂时保留此语法的原始形式,特别是因为您正在处理 Rails 3 中的范围和关系对象,而 will_paginate 还没有对此提供适当的支持(但它即将推出)。在您的“示例 2”中,您似乎只需要从每个主题中获取最近的前几个问题,并且您不会在此处执行完整的分页(例如,转到第 2 页并向前)。您不必在此处使用
paginate
方法;您可以简单地使用 ActiveRecord 的limit
:This looks like Rails 3. Be sure to use the
~> 3.0.pre2
version of the will_paginate gem.You can use the
paginate
method at the end of your chain of scopes. For example, your "example 1" would be:I see you created a custom method (
pagination
) to wrap this pattern, but it's best that you keep this syntax in original form for now, especially since you're dealing with scopes and Relation objects in Rails 3 and will_paginate doesn't have proper support for this yet (but it's coming).In your "example 2" it seems you only need to fetch the first few recent questions from each topic and that you won't perform a full-blown pagination here (like, going to page 2 and forward). You don't have to use the
paginate
method here; you can simply use ActiveRecord'slimit
: