Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use case of 'respond_to' in rails?

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

respond_to do |format|
      format.js
end

What's this respond_to, format.html, format.xml and format.js? What's their purpose and how do they work?

like image 335
Mohit Jain Avatar asked May 03 '10 06:05

Mohit Jain


People also ask

What does Respond_to do in Rails?

A respond_to shortcut it works the same way as writing the full respond_to block in index . It's a short way to tell Rails about all the formats your action knows about. And if different actions support different formats, this is a good way to handle those differences without much code.

What is Respond_to in Ruby?

respond_to is a Rails method for responding to particular request types. For example: def index @people = Person.find(:all) respond_to do |format| format.html format.xml { render :xml => @people.to_xml } end end.


2 Answers

Here's the link to the documentation

http://api.rubyonrails.org/classes/ActionController/MimeResponds/ClassMethods.html#method-i-respond_to

Its a way of responding to the client based on what they are asking for, if the client asks for HTML, Rails will send back HTML to the client, if they ask for XML then XML.

like image 78
Anand Shah Avatar answered Oct 13 '22 00:10

Anand Shah


Say you are doing this:

    class UsersController < ApplicationController

      def create
        #
        #your code
        #

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

      def edit
        #
        #your code
        #

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

    end

rather do:

    class UsersController < ApplicationController

      respond_to :xml, :json, :html

      def create
        #
        #your code
        #

        respond_with xxx

      end

      def edit
        #
        #your code
        #

        respond_with xxx

      end

    end

and thats how you keep the code DRY (Dont Repeat Yourself)

like image 34
Devaroop Avatar answered Oct 13 '22 02:10

Devaroop