Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does rails determine incoming request format?

I'm just wondering how rails knows the format of the request as to correctly enter in the famous:

respond_to do |format|
  format.html
  format.xml
  format.json
end

As an example consider this situation I have faced up. Suppose that via javascript (using jQuery) I make a POST request expliciting dataType: json

$.ajax({
      type: 'POST',
      url: 'example.com',
      data: data,
      dataType: 'json'
    });

When this request reach controller action, standing inside it with ruby debugger, I inspect @request.format and I can see that content-type is application/json. Then the controller respond to json format as expected.

But I'm confused with the format symbol especified in the routes. Suppose that a request is made to example.com/parts.json but in the request the content type is application/html or application/xml. Is the controller responding to json format or html or xml??

Thanks!

like image 517
flyer88 Avatar asked Jun 06 '11 14:06

flyer88


People also ask

What decides which controller receives Ruby?

Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.

When a request comes into a Rails application which code will run first?

The first element is the HTTP status code – 200 for a successful request, 404 for not found, etc.

What does Before_action do in Rails?

When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.

What does render JSON do in Rails?

render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.


1 Answers

The incoming Content-Type only affects the way the request is parsed. It doesn't affect the response format.

Since Rails 5.0, the response format is determined by checking for:

  1. A format parameter (e.g. /url?format=xml)
  2. The HTTP Accept header (e.g. Accept: application/json)
  3. The path extension (e.g. /url.html)

You can see this in the implementation of ActionDispatch::Http::MimeNegotation#formats. Here is an excerpt from Rails v6.1:

if params_readable?
  Array(Mime[parameters[:format]])
elsif use_accept_header && valid_accept_header
  accepts
elsif extension_format = format_from_path_extension
  [extension_format]
elsif xhr?
  [Mime[:js]]
else
  [Mime[:html]]
end
like image 145
Hosam Aly Avatar answered Oct 17 '22 09:10

Hosam Aly