We decide to service JSON and XML requests from these two actions. The index will be triggered by a GET request to /articles.json or /articles.xml. The create will be triggered by a POST request to the same paths.

respond_to

The first step is to call respond_to and list the formats our controller will respond to. This is typically done at the beginning of the controller:

Our controller will now attempt to respond to requests for HTML, JSON, or XML.

When starting out with an API, I often forget the :html in the respond_to. The application will work at first because it will match an existing view template for the rendering. But, once you start using respond_with, your responses will be blank unless you include :html here.

If you request /articles.json you will find that the application is still unsuccessfully trying to render articles.json.erb.

respond_with

You could write a view template for JSON and one for XML, but doing so is a tremendous pain. Instead, we would like to render the data directly from the controller.

Simple Rendering

In the past, we broke down each format response using respond_to in the controller action:

It led to a lot of repetition. In Rails 3, we can instead use respond_with:

1234

defindex@articles=Article.allrespond_with(@articles)end

The respond_with method will first attempt to render a matching view template for the response type, like index.json.erb or index.html.erb. If that template is not found, then the method will call .to_xml or .to_json on the object and render the result.

By combining respond_to and respond_with we can save a lot of boilerplate code that was prevalent in Rails 2.

Object Validation

But how is this technique used when we write a create action that checks object validation? We started with this:

When we pass @article to respond_with, it will actually check if the object is valid? first. If the object is not valid, then it will call render :new when in a create or render :edit when in an update.

If the object is valid, it will automatically redirect to the show action for that object.

Controlling the Redirect

Maybe you would rather redirect to the index after successful creation. You can override the redirect by adding the :location option to respond_with: