ZeroNegOne
ZeroNegOne

Reputation: 99

What is actually returned by respond_to?

respond_to do |format|
  format.html { render :html => @something }
  format.json { render :json => @something }
  format.xml { render :xml => @something }
end

Here we have three different formats: html, json, xml. So which one is actually returned? Do we have three different files ending with .html, .xml, .json? Or in other words, does respond_to render all three html, json, xml files?

Upvotes: 0

Views: 79

Answers (2)

shrikant1712
shrikant1712

Reputation: 4446

respond_to is a Rails helper method that is attached to the Controller class (or rather, its super class). It is referencing the response that will be sent to the View (which is going to the browser).

The block in your example is formatting data - by passing in a 'format' paramater in the block - to be sent from the controller to the view whenever a browser makes a request for html or json data. in rails you can write this also

class PostsController < ApplicationController
  respond_to :html, :xml, :js

  def index
    @posts = Post.all

    respond_with(@posts)
  end
end

Upvotes: 1

davidrac
davidrac

Reputation: 10738

respond_to can render each of the three, according to the current request. The right response is not what's returned from respond_to but what's actually rendered. You can find the full explanation here

Upvotes: 0

Related Questions