0

Ruby on Rails Question: Inside the controller you have seven REST actions. Almost all of them have respond to do format xml/html or json. I have no idea what this means. Can you please explain it's purpose. For example:

def index
  @tweets = Tweet.all

  respond_to do |format|
   format.html
   format.json { render json: @tweets }
  end
end

What is the purpose of the "respond to" part that contains the html and json? What do these formats do? Also, what is the difference between xml and html? Sometimes I see xml and other times html.

Thank you

user2449984
  • 915
  • 1
  • 7
  • 9
  • 1
    Duplicate? http://stackoverflow.com/questions/9492362/rails-how-does-the-respond-to-block-work – Nobita Nov 11 '13 at 17:11
  • So you can respond to requests with HTML, e.g., a person making a request from a browser, or with JSON, e.g., a client-side framework getting JSON data. XML is XML, HTML is HTML. – Dave Newton Nov 11 '13 at 17:25
  • Tweet.all is going to render all the tweets in the table, so that the client can see them. So I am confused as to the add value of "format html and json". To me the task was complete when the user sees the entire table, what does the format html and json do additionally? – user2449984 Nov 11 '13 at 17:35
  • @user2449984 HTML renders HTML. If I was an Ajax call, for example, from a client-side library or anything else using the Rails app as a web service, HTML is useless--you'd want the data to be returned in JSON format. Humans on browsers are not the only things that consume data. – Dave Newton Nov 11 '13 at 17:41

1 Answers1

1

Its just a way of telling your controller how to respond to different request types. For example your client could want html or xml information from you:

def index
 @people = Person.find(:all)

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

What that says is, "if the client wants HTML in response to this action, just respond as we would have before, but if the client wants XML, return them the list of people in XML format." (Rails determines the desired response format from the HTTP Accept header submitted by the client.)

http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

wpp
  • 7,093
  • 4
  • 33
  • 65