Rails 将公共路线附加到多条路线

Rails append common route to several routes

这是我的路线:

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

我想在上面每条路线的末尾附加一条子路线。我要追加的子路线是:

'/location/:location_id'

这样,我将能够访问:

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

我调查了路由问题,但我不确定这是否能解决我的问题。我试过这样的事情:

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

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

但显然这是错误的,它不起作用(不向 rake routes 添加任何内容)。如何实现干路由方案?

将location路由定义为关注下的资源,像这样:

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

这将生成以下路由:

$ 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

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