2013-09-06 3 views
1

Как добавить конечную точку /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] 

ответ

5

Я знаю, что вы добавили этот вопрос ruby-on-rails-3, но я собираюсь предоставить 4 решение Rails для тех, кто приходит через это в будущем.

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] 
+0

ах очень приятно. Как оказалось, мы на самом деле используем Rails 4, но я все еще привык использовать его так же, как Rails 3. Позвольте мне проверить и сообщить вам. – mehulkar

+0

Отлично работает! Тесты зеленые :) Спасибо! – mehulkar

Смежные вопросы