3

如何/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

我看到这个答案很接近,但我需要能够指定到达资源的操作。有没有更好的方法以更好的方式注入搜索路线?

%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]
4

1 回答 1

7

我知道您已经标记了这个问题ruby-on-rails-3,但我将为将来遇到此问题的任何人提供 Rails 4 解决方案。

Rails 4 引入了路由问题

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]
于 2013-09-06T18:47:22.657 回答