我在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
我现在想向配置中添加一些其他操作,例如enable
,disable
resources :installation, except: %i[index edit update show] do
resources :configuration, shallow: true, except: %i[index show] do
post :enable
post :disable
end
end
其中添加了以下内容:
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: :id
或key: id
之类的东西,但都没有达到预期的效果。可行但有点混乱的是像这样分别添加新路由:
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
在使用嵌套资源的同时,有没有更干净的方法来完成相同的事情?
答案 0 :(得分:1)
尝试这个
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
我确定它可以在导轨4/5上使用,但不确定在导轨3上可以使用。 编辑:选中,它应该可以工作。