Paginate on two collections on the same model
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 galler开发者_JAVA技巧y 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?
I'd set it up like this:
class GalleriesController < ApplicationController
def index
@galleries = Gallery.paginate(params)
end
end
class CommentsController < ApplicationController
def index
@comments = parent.comments.paginate(params)
end
def parent
@parent ||= Gallery.find(params[:gallery_id])
end
end
class PhotosController < ApplicationController
def index
@photos = parent.photos.paginate(params)
end
def parent
@parent ||= Gallery.find(params[:gallery_id])
end
end
# config/routes.rb
resources :galleries do
resources :photos
resources :comments
end
Then you just request:
/galleries/1/comments
/galleries/1/photos
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.
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.
精彩评论