为多个资源添加通​​用路由

时间:2013-09-06 18:31:48

标签: 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

我看到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]

1 个答案:

答案 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]