In Rails 3, respond_to and format.all works differently than Rails 2?

后端 未结 3 672
栀梦
栀梦 2021-02-05 05:10

the code

respond_to do |format|
  format.html
  format.json { render :json => @switches }
  format.xml { render :xml => @switches.to_xml }
  format.all { r         


        
3条回答
  •  心在旅途
    2021-02-05 05:36

    In rails3 you would write:

    respond_with(@switches) do |format|
      format.html
      format.json { render :json => @switches }
      format.xml  { render :xml  => @switches }
      format.all  { render :text => "only HTML, XML, and JSON format are supported at the moment." }
    end
    

    But this only works in correspondence with a respond_to block at the top of the file, detailing the expected formats. E.g.

    respond_to :xml, :json, :html
    

    Even in that case, if anybody for instance asks the js format, the any block is triggered.

    You could also still use the respond_to alone, as follows:

    @switches = ...
    respond_to do |format|
      format.html {render :text => 'This is html'}
      format.xml  {render :xml  => @switches}
      format.json {render :json => @switches}
      format.all  {render :text => "Only HTML, JSON and XML are currently supported"}
    end
    

    Hope this helps.

提交回复
热议问题