What does .:format mean in rake routes

2019-03-10 23:05发布

问题:

I type rake routes and I get a bunch of urls like this - /articles/:id(.:format)

My question is - what does the .:format mean? It is not clear from the Rails Guides Routing article and there are no other helpful matches for .:format on StackOverflow or google. There is a similar format which is /:controller(/:action(/:id(.:format))) which I also don't understand.

Thanks

EDIT follow up question -

If I wanted to only route HTML pages. Would it be best practice to specify something like .:html in the route or to use .:format and just write a respond_to block for format.html? Would all other formats be ignored in that latter case?

回答1:

That's the format of the file being requested. For instance, if you want an image, you'd probably have a file extension in the request - for instance, example.com/example_image.png would give you the format as png. This is then included in the request so you can vary response type based of of the format requested, need be.

For a usage example, you may want to allow a resource to be represented as a pdf, as a plain html page and as json - you'd probably write something like this:

respond_to do |format|
  format.html { ... }
  format.pdf { ... }
  format.json { ... }
end

Then have separate render calls under the respective formats.


EDIT:

Explanation of GET /:controller(/:action(/:id(.:format))) :controller#:action -

First, a bit about formatting. The parentheses mean that a given piece of data is optional. The colon means that whatever string it finds in the corresponding URL should be passed to the controller within the params hash.

This is essentially a wildcard matcher will will attempt to match a very broad number of requests to a controller. For instance, lets say this is your only route, and someone tries to get '/users'. This will map users to the UsersController, and by default call/render index within it. If someone gets users/new, the new action within the controller will be called. If id and format are called, they too will be passed along to the controller.



回答2:

.:format matches a mime type.

For instance if you send a request looking for index.html the format catches 'html' as :format.

Then in your controller it will get processed by something like

respond_to do |format|
  format.html { #do something like redirect in here }
end