Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails respond_to and various forms of html responses

I often use

respond_to do |format|
...
end

in Rails for my Restful actions, but I don't know what the ideal solution is for handling various forms of, say, html responses. For instance, view1 that calls action A might expect back html with a list of widgets wrapped in a UL tag, while view2 expects the same list of widgets wrapped in a table. How does one Restfully express that not only do I want back an html formatted response, but I want it wrapped in a table, or in a UL, OL, options, or some other common list-oriented html tag?

like image 454
Luke W Avatar asked Oct 26 '22 15:10

Luke W


1 Answers

This is the basic idea:

Controller

class ProductsController < ApplicationController

  def index

    # this will be used in the view
    @mode = params[:mode] || 'list'

    # respond_to is used for responding to different formats
    respond_to do |format|
      format.html            # index.html.erb
      format.js              # index.js.erb
      format.xml do          # index.xml.erb
        # custom things can go in a block like this
      end
    end
  end

end

Views

<!-- views/products/index.html.erb -->
<h1>Listing Products</h1>

<%= render params[:mode], :products => @products %>


<!-- views/products/_list.html.erb -->
<ul>
  <% for p in products %>
  <li><%= p.name %></li>
  <% end %>
</ul>


<!-- views/products/_table.html.erb -->
<table>
  <% for p in products %>
  <tr>
    <td><%= p.name %></td>
  </tr>
  <% end %>
</table>

Usage:

You can link to other views "modes" using:

<%= link_to "View as list",   products_path(:mode => "list") %>
<%= link_to "View as table",  products_path(:mode => "table") %> 

Note: You'll want to do something to ensure that the user doesn't attempt to specify an invalid view mode in the URL.

like image 170
maček Avatar answered Nov 25 '22 11:11

maček