您可以通过查看路由定义来确定路由助手需要多少个参数。
例如,您可能有以下路由文件:
resources :users
如果你跑了rake routes
在命令行中你会看到类似这样的内容:
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
or _url
获取路线助手的名称。
第三列显示模式。在这里您可以弄清楚争论的内容。参数是以冒号为前缀的部分,可选参数显示在括号中。例如edit_user
路线有模式/users/:id/edit(.:format)
其中包含一个必需参数(id
) 和一个可选参数 (format
),这告诉我我需要将至少一个参数传递给edit_user_path
or edit_user_url
helper:
edit_user_path(1) # => "/users/1/edit"
edit_user_path(2, :html) # => "/users/2/edit.html"
您还可以使用模式中的参数名称作为哈希中的键:
edit_user_path(id: 3, format: 'js') # => "/users/3/edit.js"
最后,您可以添加额外的参数,这些参数将成为查询字符串的一部分:
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 路由指南中有关列出现有路由的部分 http://guides.rubyonrails.org/routing.html#listing-existing-routes欲了解更多信息rake routes
.