【问题标题】:How to add extra parameter to resources in routes如何向路由中的资源添加额外参数
【发布时间】:2013-12-04 19:15:16
【问题描述】:

我希望resources 生成的成员路由包含附加参数。

类似:

resources :users

以下路线:

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

有什么想法吗?

【问题讨论】:

  • 你搞清楚了吗?
  • @tommyalvarez 为我自己的问题添加了答案。

标签: ruby-on-rails routing routes


【解决方案1】:

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]

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我一定需要使用资源方法
    【解决方案3】:
    resources :users, path: 'user' do
      collection do
        get ':id/:some_param', action: :action_name 
        get ':id/:some_param/edit', action: :custom_edit
      end
    end
    

    【讨论】:

    • 像您一样手动添加路由不是问题。我需要避免它。我必须只使用资源方法。
    • 然后修补动作包。
    • 为什么一定要?只是好奇,你的用例是什么?
    猜你喜欢
    • 2010-12-16
    • 2018-04-08
    • 2013-12-15
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    相关资源
    最近更新 更多