对同一模型上的两个集合进行分页
我计划在应用程序中的几个模型中添加一些分页,但我觉得我在这里缺少一个关键概念。这是我的应用程序:
class Gallery < ActiveRecord::Base
has_many :photos
has_many :comments
end
class GalleryController < ApplicationController
def show
# some process here
@gallery = Gallery.find(params[:id])
end
end
我希望能够对我正在显示的给定图库的照片和评论进行独立分页。我需要使用 AJAX 来完成此操作,并且我有一种感觉,使用照片或图库的参数调用“show”太过分了(即,如果我只查找照片或评论,为什么我需要找到图库)。
我应该如何设计这个功能?
在这里调用 GalleryController.show 的替代方法是什么?
I am planning to add some pagination to a couple of models in my application and I feel like I am missing a key concept here. Here is my application:
class Gallery < ActiveRecord::Base
has_many :photos
has_many :comments
end
class GalleryController < ApplicationController
def show
# some process here
@gallery = Gallery.find(params[:id])
end
end
I would like to be able to paginate independently on both the photos and comments for the given gallery that I am displaying. I need this to be done with AJAX and I have a feeling that calling 'show' with a parameter for photos or gallery is overkill (ie. why would I need to find the gallery if I am only looking for photos or comments).
How should I design this feature?
What is the alternative to calling GalleryController.show here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会这样设置:
然后您只需请求:
查看此嵌套模型的 inherited_resources gem图案。
但理想情况下,您希望通过一个请求获得这一切。查看 这篇关于 Rails 中演示者模式的文章。
希望有帮助。
I'd set it up like this:
Then you just request:
Check out the inherited_resources gem for this nested model pattern.
But ideally you'd want to get this all in one request. Check out this post on the Presenter Pattern in Rails.
Hope that helps.
是的,我绝对推荐使用inherited_resources,因为它可以为您节省大量样板代码。只需按照viatropos所述设置这些资源,添加JSON响应程序(使用inherited_resources,就像将
respond_to :json, :html
添加到控制器一样简单)。然后在ajax端使用一个诱人的插件,例如 jquery.tmpl 或 mustache.js 或其他任何内容,为每个资源预渲染一个项目模板,然后使用 ajax 检索分页数据作为 JSON 和将其渲染到您的模板中。这非常简单,但如果您需要一步一步的操作方法,请询问。yes, i'd absolutely recommend using inherited_resources, as it saves you a lot of boilerplate code. just set up these resources as described by viatropos, add JSON-responder (with inherited_resources, its as easy as adding
respond_to :json, :html
to your controller). then on the ajax side use a tempting plugin, like jquery.tmpl or mustache.js or whatever, pre-render an item template for each resource, and then use ajax to retrieve your paginated data as JSON and render it into your templates. it's incredibly easy, but if you need a step by step howto, just ask.