2 Replies - 2751 Views - Last Post: 18 July 2011 - 09:32 AM Rate Topic: -----

#1 heikodachi  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 01-April 11

respond_to do |format|

Posted 17 July 2011 - 01:45 AM

Okay, I am trying to get to grips with controllers in Ruby on Rails but I am having trouble getting my head around the following line of code:

class PostsController < ApplicationController

 def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end

end



Thanks!
Is This A Good Question/Topic? 0
  • +

Replies To: respond_to do |format|

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2132
  • View blog
  • Posts: 3,263
  • Joined: 21-June 11

Re: respond_to do |format|

Posted 17 July 2011 - 10:14 PM

respond_to allows you to execute different code depending on which format was requested. In this case you can read the code as:

If the requested format is html, do nothing special (i.e. render the html view normally).
If the requested format is xml, execute render :xml => @posts.
Was This Post Helpful? 1
  • +
  • -

#3 NotarySojac  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 53
  • View blog
  • Posts: 428
  • Joined: 30-September 10

Re: respond_to do |format|

Posted 18 July 2011 - 09:32 AM

I began, but did not finish, a writeup somewhat on this subject. This link has a little more information regarding the power of the lines of code you're grappling with.

http://www.digitalho...-json-requests/

I might be doing some work on the write today so I'll post it if I get it finished (damn it's hot today though, I don't wanna think too hard).


Oh, ps:
Try typing YOURAPP.com/YourController/index.xml I *think* that will show you the xml version of the index.

Edit: It's done, but it's probably not something you need atm

This post has been edited by NotarySojac: 18 July 2011 - 11:39 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1