Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a common route for multiple resources

How do I add the /search endpoint to all these resources in one go?

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

I saw this answer which is close, but I need to be able to specify the actions for reach resource. Is there a better way to inject the search route in a better way?

%w(one two three four etc).each do |r|
  resources r do
    collection do
      post 'common_action'
    end
  end
end

Something like this?

resources :posts, only [:index, :show, :create, :search]
like image 999
mehulkar Avatar asked Oct 29 '25 18:10

mehulkar


1 Answers

I know you've tagged this question ruby-on-rails-3, but I'm going to provide the Rails 4 solution for anyone who comes across this in the future.

Rails 4 introduces 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]
like image 54
deefour Avatar answered Oct 31 '25 07:10

deefour