Yarin
Yarin

Reputation: 183499

Why is respond_to used in this example?

It's been asked multiple times, but I'm still frankly confused about the utility of respond_to, so I'm hoping to get an explanation of it in context.

In this Railscast about creating RESTful APIs, Ryan Bates puts a respond_to :json directive at the top of his controller:

class ProductsController < ApplicationController
  respond_to :json

  def index
    respond_with Product.all
  end

However, he's already placed his routes in a block that specifies JSON as the default format:

  namespace :api, defaults: {format: 'json'} do
    scope module: :v1, constraints: ApiConstraints.new(version: 1) do
      resources :products
    end

Furthermore, I tried putting the same directive in my controller, but was still able to serve .html responses.

So if respond_to doesn't set the default response format, and doesn't prevent other response formats, what purpose does it serve?

Upvotes: 0

Views: 55

Answers (2)

junil
junil

Reputation: 768

respond_to defines mime types that are rendered by default when invoking respond_with. respond_to :json specifies all actions in the controller respond to json

Reference: http://api.rubyonrails.org/classes/ActionController/MimeResponds/ClassMethods.html

May be you have added respond_to :html in ApplicationController.That's why they are still responding to html requests

Upvotes: 0

Logan Serman
Logan Serman

Reputation: 29870

respond_to :html is on ActionController::Base by default. That is why you can respond with HTML still.

The format in the routes basically say that anything requesting routes in that namespace will automatically have their 'format' parameter set to 'json', so even if the API clients don't specifically request JSON, it will be set to JSON as a default.

respond_to :json is just saying that respond_with should respond with JSON if JSON is requested.

Upvotes: 1

Related Questions