有没有人找到一种合理的方法将 will_paginate 的东西移动到 Rails 3 的模型中?
尝试在rails 3中使用will_paginate gem,我想将尽可能多的业务转移到模型中,但这似乎很困难,而且我还没有看到太多。通常,您会执行以下操作:
Resource.where(:foo => :bar).paginate(:page => params[:page], :per_page => 10)
是否有办法将 params[:page]
放入模型中?在那里无法访问 params
。我的理想是以某种方式将其纳入范围
。
Trying to use the will_paginate gem in rails 3, and I want to move as much of this business into the model as possible, however it seems difficult, and I haven't seen much on it. Usually, you would do something like:
Resource.where(:foo => :bar).paginate(:page => params[:page], :per_page => 10)
Is there anyway to get that params[:page]
into the model? params
isn't accessible there. My ideal would be to somehow work this into a scope
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果模型的方法将参数作为参数并且参数由控制器传递给模型,则参数在模型的方法中可用。但是,最好只传递 params[:page],因为模型不应该知道有关参数的任何信息。例如,请参阅此示例。
分页主要不是业务逻辑:它与如何呈现数据有关。因此,涉及的大多数代码不属于模型。然而,will_paginate 提供了方便的方法来获取模型的结果 0-15、15-30...,而列出这些列表只是 activerecord 模型的一种能力,这就是它确实属于那里的原因。
The params are available in a method of a model if the method takes the params as a parameter and the params are passed to the model by the controller. However, it would be better to pass only the params[:page], because the model should not know anything about the params. See, for instance, this example.
Pagination is mostly not business logic: it's about how you present the data. Hence most code involved does not belong in a model. However, will_paginate provides convenience methods to obtain results 0-15, 15-30, ... of a model and coughing up those lists is simply an ability of an activerecord model, which is why it does belong there.