简体   繁体   中英

Rails append common route to several routes

Here is my route:

resources :campaigns,   only: [:index, :show]
get '/signs/:sign_id',  to: 'signs#show',      as: 'sign'
#...others like this...

I'm wanting to append a sub-route to the end of each of the routes above. The sub-route I want to append is:

'/location/:location_id'

This way, I would be able to access:

/campaigns/1
/campaigns/1/location/2
/signs/13
/signs/1/location/12
etc.

I looked into Routing Concerns, but I'm not sure if that would solve my problem. I tried something like this:

#routes.rb
concern :locationable do
  member do
    get '/location/:location_id'
  end
end

resources :campaigns, only: [:show], concerns: :locationable

But obviously this is wrong and it does not work (does not add anything to rake routes ). How can I achieve a dry routing solution?

Define the location route as a resource under the concern, like this:

concern :locationable do  
  resources :locations, only: :show
end
resources :campaigns, only: :show, concerns: :locationable
resources :signs, only: :show, concerns: :locationable

That will generate the following routes:

$ rake routes
           Prefix Verb URI Pattern                                     Controller#Action
campaign_location GET  /campaigns/:campaign_id/locations/:id(.:format) locations#show
         campaign GET  /campaigns/:id(.:format)                        campaigns#show
    sign_location GET  /signs/:sign_id/locations/:id(.:format)         locations#show
             sign GET  /signs/:id(.:format)                            signs#show

Source: http://guides.rubyonrails.org/routing.html#routing-concerns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM