rails respond_to和各种形式的HTML响应

时间:2010-05-12 15:22:35

标签: ruby-on-rails rest

我经常使用

respond_to do |format|
...
end
在Rails中我的Restful动作,但我不知道理想的解决方案是什么,处理各种形式的,例如,html响应。例如,调用操作A的view1可能期望返回带有包含在UL标记中的小部件列表的html,而view2期望包含在表中的相同小部件列表。一个人如何巧妙地表达我不仅要回复html格式的响应,而且我想将它包装在表格中,或者包含在UL,OL,选项或其他一些常见的面向列表的html标签中?

3 个答案:

答案 0 :(得分:3)

这是基本的想法:

控制器

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/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>

用法:

您可以使用以下方式链接到其他视图“模式”:

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

注意:您需要采取措施确保用户不会尝试在网址中指定无效的视图模式。

答案 1 :(得分:0)

我认为你在这里走错了路。首先,视图不会调用操作,反之亦然。其次,respond_to用于显示完全不同的格式(即html,xml,js等),而不是不同的模板。

答案 2 :(得分:0)

检查默认路线的这种变体:

 map.connect ':controller/:action/:id.:format'

请注意,它允许您通过将其作为扩展名传递来设置格式。例如,我有时会为多个消费者提供需要不同XML格式的应用程序。

因此,例如,在一次放置中,iphone应用程序使用格式'xmlm'(对于XML Mobile),而java消费者使用'xml',因为它正在使用完整的序列化。这让我可以将该指标用作顶级格式。

respond_to do |format|
 format.xml{  render :xml => @people.to_xml  }
 format.xmlm { do other stuff }
end

此页面对您有所帮助,并包含实现此内容所需的所有信息(请特别注意有关自定义mime类型的部分),请务必查看评论:http://apidock.com/rails/v2.3.4/ActionController/MimeResponds/InstanceMethods/respond_to