Rails将通用路由附加到多个路由

时间:2015-07-07 02:37:04

标签: ruby-on-rails ruby-on-rails-4 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添加任何内容)。如何实现干路由解决方案?

1 个答案:

答案 0 :(得分:1)

将位置路线定义为关注点下的资源,如下所示:

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