views:

28

answers:

1

I'm a newcomer to Rails, and have been following the tutorial on the rails webpage. Using the scaffold instruction to create a "post" model, I found that the new action in the controller has a special directive for XML format:

def new
  @post = Post.new

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

I can't see the reasoning for supporting an XML request when creating a new post. Browsing to /posts/new.xml returns nothing. What is the purpose of this?

+2  A: 

The reasoning for it behind the new action is simply to provide a xml client with the default data (or something else if you want).

The format directive is being used by all routes, and you don't need to support a format unless you want to.

The above code could might as well have looked like:

respond_to do |format|
  format.html # renders new.html.erb
  format.xml  { render :xml => {:message => "XML is not supported"} }
  format.json { render :text => @post.to_json }
  format.js # renders new.js.erb
end

Also, this is not limited to the new action, but is available in all your actions. The format to use is either taken from the url (if the route is set up to use it), or from the HTTP-Accept header that the browser sends.

Jimmy Stenke