meh*_*kar 2 ruby-on-rails ruby-on-rails-4
如何/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
Run Code Online (Sandbox Code Playgroud)
我看到这个答案很接近,但我需要能够为触及资源指定操作.有更好的方法以更好的方式注入搜索路径吗?
%w(one two three four etc).each do |r|
resources r do
collection do
post 'common_action'
end
end
end
Run Code Online (Sandbox Code Playgroud)
像这样的东西?
resources :posts, only [:index, :show, :create, :search]
Run Code Online (Sandbox Code Playgroud)
我知道你已经标记了这个问题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]
Run Code Online (Sandbox Code Playgroud)