0
#some instance variables
respond_to do |format|
  format.html
  format.xml {...}
  format.json {...}
end

Does respond_to simply send all instance variables to the next webpage or it does something more?

I'm wondering how much data would be sent by respond_to. For example, if I have many instance variables @one @two @three etc. Are they all sent by respond_to? Any other data would be bundled and sent as well? ?

OneZero
  • 11,556
  • 15
  • 55
  • 92

2 Answers2

0

You instance variables will not be sent anywhere without your direction.

You probably have a .html.erb template that renders the instance variables when an HTML request is received (format.html).

For the xml and json responses, you need to tell Rails what to do. For instance, you could supply a template .xml.builder. Rails can also render certain structures (arrays etc.) for you automatically, simply by calling render json: @one

Pieter Jongsma
  • 3,365
  • 3
  • 27
  • 30
0

Rails goes through the registered formats and tries to find a compatible format, otherwise, it will raise an error.

Example:

def index
  @stories = Story.all
end

index action does not have a respond_to block. If a client asks to get the page in TEXT format, it will lead to the following exception:

ActionView::MissingTemplate (Missing template blogs/index ... with { ... :formats=>[:text], ...})

We can easily fix this by adding a respond_to block:

def index
  @stories = Story.all

  respond_to do |format|
    format.html
    format.js 
  end
end

After the change, the client will get 406 error when the format is not supported. Also, your index action will respond to two new formats: js and HTML.

This article explains all the ways you can use respond_to blocks.

Nesha Zoric
  • 6,218
  • 42
  • 34