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?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With