如何在路由资源中添加额外参数

时间:2013-12-04 19:15:16

标签: ruby-on-rails routing routes

我希望resources生成的成员路由包含其他参数。

类似的东西:

resources :users

以下路线:

users/:id/:another_param
users/:id/:another_param/edit

有什么想法吗?

3 个答案:

答案 0 :(得分:5)

resources方法不允许这样做。但是我们可以使用path选项(包括额外的参数)来做类似的事情:

resources :users, path: "users/:another_param" 

这将生成如下网址:

users/:another_param/:id
users/:another_param/:id/edit 

在这种情况下,我们将需要手动将:another_param的值发送给路由助手:

edit_user_path(@user, another_param: "another_value")
# => "/users/another_value/#{@user.id}/edit"

如果已设置默认值,则无需传递:another_param值:

resources :users, path: "users/:another_param", defaults: {another_param: "default_value"}

edit_user_path(@user) # => "/users/default_value/#{@user.id}/edit"

或者我们甚至可以使多余的参数在路径中不必要:

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: ""}

如果仅需要某些操作的额外参数,则可以这样做:

 resources :users, only: [:index, :new, :create]
 # adding extra parameter for member actions only
 resources :users, path: "users/:another_param/", only: [:show, :edit, :update, :destroy]

答案 1 :(得分:2)

resources :users, path: 'user' do
  collection do
    get ':id/:some_param', action: :action_name 
    get ':id/:some_param/edit', action: :custom_edit
  end
end

答案 2 :(得分:1)

你可以做一些更明确的事情,比如

 get 'my_controller/my_action/:params_01/:params_02', :controller => 'my_controller', :action => 'my_action'