rails 中的 url helper 文档在哪里?
我如何知道 url 助手在 Rails 中采用什么参数?例如,我怎么知道 url helper 只接受下面的一个参数?我知道这些方法是元编程的,但它们的文档在哪里?
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 is their documentation?
link_to "New Ticket", new_project_ticket_path(@project)
您可以通过查看路由定义来确定路由助手需要多少个参数.
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
如果你在命令行运行 rake routes
你会看到这样的:
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
第一列为您提供路线名称.您可以附加 _path
或 _url
以获取路由助手的名称.
The first column gives you the name of the route. You can append _path
or _url
to get the name of a route helper.
第三列显示模式.在这里你可以弄清楚参数是什么.参数是以冒号为前缀的部分,可选参数显示在括号中.例如,edit_user
路由的模式为 /users/:id/edit(.:format)
,其中包含一个必需的参数 (id
) 和一个可选参数(format
),它告诉我我需要将至少一个参数传递给 edit_user_path
或 edit_user_url
助手:
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"
查看Rails 路由指南中关于列出现有路由的部分了解更多信息关于rake 路线
的信息.
See the Rails Routing Guide's section on Listing Existing Routes for more information about rake routes
.