What does (.:format) mean in rake routes' outp

2019-02-06 04:37发布

问题:

What does (.:format) mean in rake routes' output?

users GET    /users(.:format)          users#index

回答1:

If you check the index action of your Users Controller then you will see something like this

def index
  @users = User.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @users }
  end
end

So, this format is the type of response which will be generated.

In routes, a placeholder for the type of response is created irrespective of whatever format has been defined in the action of the controller.

So, if your URL is something like :-

users GET /users        --> users/index.html.erb will be rendered
users GET /users.json   --> users/index.json.erb will be rendered

Similarly, if you want response in PDF or xls format, then you just have to define format.pdf or format.xls and also you have to define these new MIME types which are not there by default in rails in some initializer file.

So, then if a request is made like :-

users GET /users.xls     --> users/index.xls.erb will be rendered

Your routes file will then just look for the format.xls in the index action and respective view file means users/index.xls.erb will be rendered.