为其他资源操作指定参数名称

Specify parameter name for additional resource actions

我在 routes.rb

中指定了一些嵌套资源
resources :installation, except: %i[index edit update show] do
     resources :configuration, shallow: true, except: %i[index show] 
end

生成以下路线:

installation_configuration_index POST   /installation/:installation_id/configuration(.:format)     configuration#create
  new_installation_configuration GET    /installation/:installation_id/configuration/new(.:format) configuration#new
              edit_configuration GET    /configuration/:id/edit(.:format)                          configuration#edit
                   configuration PATCH  /configuration/:id(.:format)                               configuration#update
                                 PUT    /configuration/:id(.:format)                               configuration#update
                                 DELETE /configuration/:id(.:format)                               configuration#destroy
              installation_index POST   /installation(.:format)                                    installation#create
                new_installation GET    /installation/new(.:format)                                installation#new
                    installation DELETE /installation/:id(.:format)                                installation#destroy

我现在想在配置中添加一些额外的操作,例如enabledisable

resources :installation, except: %i[index edit update show] do
  resources :configuration, shallow: true, except: %i[index show] do
    post :enable
    post :disable
  end
end

whichs 添加了以下内容:

 configuration_enable POST   /configuration/:configuration_id/enable(.:format)          configuration#enable
 configuration_disable POST   /configuration/:configuration_id/disable(.:format)         configuration#disable

这很好,除了这些新操作使用参数 :configuration_id 而不是 :id。这使得使用 before_actions 检查整个控制器的参数有效性变得有点烦人。

我想结束类似于以下内容:

 configuration_enable POST   /configuration/:id/enable(.:format)          configuration#enable
 configuration_disable POST   /configuration/:id/disable(.:format)         configuration#disable

我已经搜索并找到了使用 param: :idkey: id 之类的东西,其中 none 达到了预期的效果。有效但有点混乱的是像这样单独添加新路由:

post 'configuration/:id/enable', action: 'enable', as: 'configuration/enable', to: 'configuration#enable'
post 'configuration/:id/disable', action: 'disable', as: 'configuration/disable', to: 'configuration#disable'
resources :installation, except: %i[index edit update show] do
  resources :configuration, shallow: true, except: %i[index show]
end

我有更简洁的方法来完成同样的事情,同时仍然使用嵌套资源吗?

试试这个

resources :installation, except: %i[index edit update show] do
  resources :configuration, shallow: true, except: %i[index show] do
    post :enable, :on => :member
    post :disable, :on => :member
  end
end

或者这个

resources :installation, except: %i[index edit update show] do
  resources :configuration, shallow: true, except: %i[index show] do
    member do
      post :enable
      post :disable
    end
  end
end

我确定它适用于 rails 4/5,不确定适用于 rails 3。 编辑:已检查,它应该可以工作。