chu*_*off 8 routing routes ruby-on-rails
我希望生成的成员路由resources包含其他参数.
就像是:
resources :users
Run Code Online (Sandbox Code Playgroud)
以下路线:
users/:id/:another_param
users/:id/:another_param/edit
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?
resources方法不允许这样做。但是我们可以使用path包含额外参数的选项来做类似的事情:
resources :users, path: "users/:another_param"
Run Code Online (Sandbox Code Playgroud)
这将生成如下网址:
users/:another_param/:id
users/:another_param/:id/edit
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们将需要:another_param手动将价值发送给路由助手:
edit_user_path(@user, another_param: "another_value")
# => "/users/another_value/#{@user.id}/edit"
Run Code Online (Sandbox Code Playgroud)
:another_param如果已设置默认值,则不需要传递值:
resources :users, path: "users/:another_param", defaults: {another_param: "default_value"}
edit_user_path(@user) # => "/users/default_value/#{@user.id}/edit"
Run Code Online (Sandbox Code Playgroud)
或者我们甚至可以使多余的参数在路径中不必要:
resources :users, path: "users/(:another_param)"
edit_user_path(@user) # => "/users/#{@user.id}/edit"
edit_user_path(@user, another_param: "another_value")
# => "/users/another_value/#{@user.id}/edit"
# The same can be achieved by setting default value as empty string:
resources :users, path: "users/:another_param", defaults: {another_param: ""}
Run Code Online (Sandbox Code Playgroud)
如果我们仅需要某些操作的额外参数,则可以这样完成:
resources :users, only: [:index, :new, :create]
# adding extra parameter for member actions only
resources :users, path: "users/:another_param/", only: [:show, :edit, :update, :destroy]
Run Code Online (Sandbox Code Playgroud)
你可以做一些更明确的事情,例如
get 'my_controller/my_action/:params_01/:params_02', :controller => 'my_controller', :action => 'my_action'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6245 次 |
| 最近记录: |