【问题标题】:Rails append common route to several routesRails 将公共路线附加到多条路线
【发布时间】:2015-07-07 02:37:03
【问题描述】:

这是我的路线:

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 添加任何内容)。如何实现干路由解决方案?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 routes


    【解决方案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

    【讨论】:

    • 编辑:行得通!但是,我希望可定位的路由指向资源的控制器,而不是关注的控制器。例如,/campaigns/:campaign_id/locations/:id 应该指向 campaigns#show
    • 没关系,我在资源行中添加了to: 'campaigns#show,它的工作正常。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-02-24
    • 2019-11-28
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2019-04-20
    相关资源
    最近更新 更多