I know this question has been asked in part a few other times on SO but I was curious about doing it a different way. In my Ruby on Rails app I have an action called list on my UsersController.rb controller. I want this list to respond to 3 different things
- The page itself. Rending the whole page of users I specify
- A JSON list of users for the page I specify
- A partial view of just the rows for the page I’m specifying formatted as HTML.
Imagine a full page (header, footer, everything) with a table that has page 1 of users. When I click page 2 I want to kick off an ajax request back to the same controller action to give me just the html rows for page 2. I also want to persist my JSON API still allowing my controller to return JSON lists when asked. I imagine it looking someting like this.
class UsersController < ApplicationController
def list
respond_to do |format|
format.html # RETURNS MY VIEW
format.json # RETURNS MY JSON LIST
format.partial_html # RETURNS MY PARTIAL HTML
end
end
end
Is there anyway to accomplish this in RoR? Or am I doomed into having to create another action in my controller just to return technically the same data?
Could I make this happen by specifying my own MIME type? Should I snake in the partial as an XML return type?
format.json the third line.app/views/users/_html_rows.html.erb.You will have
app/views/users/list.html.erbwith the full html content, which will be something like this:You will have
app/views/users/_html_rows.html.erbwith:Then you will have
app/views/users/list.js.erbwith:This probably will solve your problem.