Where is the documentation on url helpers in rails?

前端 未结 3 1434
无人及你
无人及你 2021-02-01 15:39

How do I know what arguments url helpers take in Rails? For example, how do I know url helper takes just one parameter below? I know these methods are metaprogrammed but where i

3条回答
  •  眼角桃花
    2021-02-01 16:32

    You can determine how many parameters a route helper requires by looking at the route definition.

    For example, you might have this routes file:

    resources :users
    

    If you ran rake routes at the command line you would see something like this:

        users GET    /users(.:format)          users#index
              POST   /users(.:format)          users#create
     new_user GET    /users/new(.:format)      users#new
    edit_user GET    /users/:id/edit(.:format) users#edit
         user GET    /users/:id(.:format)      users#show
              PUT    /users/:id(.:format)      users#update
              DELETE /users/:id(.:format)      users#destroy
    

    The first column gives you the name of the route. You can append _path or _url to get the name of a route helper.

    The third column shows the pattern. This is where you can figure out what the arguments are. Arguments are the parts prefixed with a colon, and optional arguments are shown in parentheses. For example the edit_user route has the pattern /users/:id/edit(.:format) which contains one required argument (id) and one optional argument (format), which tells me I need to pass at least one argument to the edit_user_path or edit_user_url helper:

    edit_user_path(1) # => "/users/1/edit"
    edit_user_path(2, :html) # => "/users/2/edit.html"
    

    You can also use the argument names from the pattern as keys in a hash:

    edit_user_path(id: 3, format: 'js') # => "/users/3/edit.js"
    

    Finally, you can add extra arguments which will become part of the query string:

    edit_user_path(id: 4, format: 'json', foo: 1) # => "/users/4/edit.json?foo=1"
    edit_user_path(5, bar: 2) # => "/users/5/edit?bar=2"
    

    See the Rails Routing Guide's section on Listing Existing Routes for more information about rake routes.

提交回复
热议问题