My rails project is paginating the HTML format but not the the others. Can someone suggest a more elegant approach to dealing with the difference in getting the @contacts collection? Perhaps the pagination version should be a different method that only supports HTML?
def index
if request.format.to_sym == :html
@contacts = Contact.paginate(page: params[:page]).search(params[:search])
else
@contacts = Contact.search(params[:search])
end
respond_to do |format|
format.html { render html: @contacts }
format.mobile { render mobile: @contacts }
format.json { render json: @contacts }
format.xml { render xml: @contacts.to_xml }
end
end
My solution was to add paginate as a RESTful resource in routes.rb which automagically gives me the route helper method: paginate_contacts_path
resources :contacts do
collection do
get 'paginate'
end
end
and to have a separate paginate method in ContactsController
def index
@contacts = Contact.search(params[:search])
respond_to do |format|
format.html { render html: @contacts }
format.mobile { render mobile: @contacts }
format.json { render json: @contacts }
format.xml { render xml: @contacts.to_xml }
end
end
def paginate
@contacts = Contact.paginate(page: params[:page]).search(params[:search])
respond_to do |format|
format.html
end
end
Strongly prefer a separate method because this creates inconstancies and makes the piece less testable. Also you would, in for example documentation, need to create exceptions.
Another way is to handle this with some parameter. Now it suddenly (when you only change views) returns different data. That might look like an error for an unknown developer and might raise issues.
So don’t do it magically, clear parameter or separate method.