【问题标题】:Rails routes inside resources :blah do资源中的 Rails 路由:blah do
【发布时间】:2013-09-09 22:25:26
【问题描述】:

到目前为止,我的 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

【问题讨论】:

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


    【解决方案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 对象传递给它。

    【讨论】:

    • 没错,当我在资源块中命名它时,它会向它添加东西,但在外面这样做效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2011-01-17
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多