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!
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.
The first element is the HTTP status code – 200 for a successful request, 404 for not found, etc.
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.
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.
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:
format
parameter (e.g. /url?format=xml
)Accept
header (e.g. Accept: application/json
)/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With