What does .:format mean in rake routes

守給你的承諾、 提交于 2019-12-31 08:44:21

问题


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


来源:https://stackoverflow.com/questions/20320263/what-does-format-mean-in-rake-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!