Rails路由资源内部:blah do

时间:2013-09-05 22:59:41

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

到目前为止,我的routes.rb文件看起来像这样:

resources :games do
  resources :planets do
    member do
      get 'index' as: :play_game
    end
  end
end

创建这些(当我检查rake路线时)

play_game_game_planet GET    /games/:game_id/planets/:id/index(.:format) planets#index
         game_planets GET    /games/:game_id/planets(.:format)           planets#index
                      POST   /games/:game_id/planets(.:format)           planets#create
     new_game_planet  GET    /games/:game_id/planets/new(.:format)       planets#new
    edit_game_planet  GET    /games/:game_id/planets/:id/edit(.:format)  planets#edit
         game_planet  GET    /games/:game_id/planets/:id(.:format)       planets#show
                      PATCH  /games/:game_id/planets/:id(.:format)       planets#update
                      PUT    /games/:game_id/planets/:id(.:format)       planets#update
                      DELETE /games/:game_id/planets/:id(.:format)       planets#destroy

但我想要的路径(类似于第二行)

play_game GET    /games/:game_id/planets(.:format)           planets#index

1 个答案:

答案 0 :(得分:1)

您已经在上面定义了game_planets /games/:game_id/planets(.:format) planets#index路由 - 指定的路由为game_planets。所以我假设你想要的是命名路线的不同名称?

如果那就是你所追求的并且你不能被告知(也就是说其他Rails开发人员会想到为什么非标准的命名路由结构)那么你可以这样做:

resources :games do
  resources :planets
end

get 'games/:game_id/planets', 'planets#index', as: 'play_game'

这实际上创建了一个带有特殊命名路由的重复路由。但我建议不要这样做,因为:

  1. 索引操作应使用复数命名路由(至少使用as: 'play_games'
  2. 这不标准。命名路由play_game会让我觉得有一个PlayController有一个嵌套的Game控制器,这将是一个需要show对象的play操作传入它。