我有这个路由:
resources :placements, only: :index do
collection do
put :update_all
delete :destroy_all
end
end
resources :designs, only: :index do
collection do
put :update_all
delete :destroy_all
end
end
# etc...
代码太多,看起来很难看。有没有办法得到这样的东西:
with_options only: :index, collection: { update_all: :put, destroy_all: :delete } do
resources :placements
resources :designs
end
提前致谢! :)
PS:这段代码看起来不错,但不起作用:(
答案 0 :(得分:2)
Rails 4有routing concerns可用于执行此操作:
concern :standard_routing do
collection do
put :update_all
delete :destroy_all
end
end
resources :placements, only: :index, concerns: :standard_routing
resources :designs, only: :index, concerns: :standard_routing
也就是说,路由DSL只是Ruby代码,do
块只是块!因此,即使没有任何特殊支持,您也可以将其包装成一个简单易用的生成器,或者重用procs。
def standard_actions_for(*resources)
Array(resources).each do |resource|
self.resources resource, only: :index do
collection do
put :update_all
delete :destroy_all
end
end
end
end
standard_actions_for :placements, :designs
或:
standard_routing = Proc.new do
collection do
put :update_all
delete :destroy_all
end
end
resources :placements, only: index, &standard_routing
resources :designs, only: index, &standard_routing