如何一次性将/search
端点添加到所有这些资源?
MyCoolApp::Application.routes.draw do
resources :posts, only [:index, :show, :create] do
collection { get :search }
end
resources :authors, only [:index, :show] do
collection { get :search }
end
resources :comments, only: [:index, :show] do
collection { get :search }
end
resources :categories, only: [:index, :show] do
collection { get :search }
end
resources :tags, only: [:index] do
collection { get :search }
end
end
我看到this answer已接近,但我需要能够为触及资源指定操作。是否有更好的方式以更好的方式注入搜索路径?
%w(one two three four etc).each do |r|
resources r do
collection do
post 'common_action'
end
end
end
这样的东西?
resources :posts, only [:index, :show, :create, :search]
答案 0 :(得分:6)
我知道您已对此问题ruby-on-rails-3
进行了标记,但我将为将来遇到此问题的任何人提供Rails 4解决方案。
Rails 4引入了 Routing Concerns
concern :searchable do
collection do
get :search
end
end
resources :posts, only [:index, :show, :create], concerns: [:searchable]
resources :authors, only [:index, :show], concerns: [:searchable]
resources :comments, only: [:index, :show], concerns: [:searchable]
resources :categories, only: [:index, :show], concerns: [:searchable]
resources :tags, only: [:index], concerns: [:searchable]