【问题标题】:Custom route redirect to wrong action自定义路由重定向到错误的操作
【发布时间】:2017-01-05 03:02:05
【问题描述】:

我的路线文件中有以下内容:

  resources :exercises, shallow: true do
    resources :questions do
      resources :test_cases do
        member do
          post :run, to: 'test_cases#run'
        end
      end
    end
  end

  get 'test_cases/test', to: 'test_cases#test'

我的问题在于资源之外的 test 路由。检查可用路线我有我想要的:

test_cases_test GET    /test_cases/test(.:format)                       test_cases#test

但是,如果我从视图中调用test_cases_test_url,我将被重定向到test_cases#show,而不是test_cases#testThis question 在不同的情况下是相同的问题。我不想遵循已接受的答案,因为如果我将get 'test', to: 'test_cases#test' 放入我的resources :test_casesmember 块之外,我将在我的路线中获得question_id,并在member 块中获得test_case_id。我不需要这些 ID。

我可以选择让我想要的路线(test_cases/test)工作吗?

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    我认为您正在匹配 test_cases#show 方法,因为它与 test_cases/test url 具有相同的模式,并且它出现在之前。只需将test_cases/test get 路由移动到路由文件的顶部

    get 'test_cases/test', to: 'test_cases#test'
    
    resources :exercises, shallow: true do
      resources :questions do
        resources :test_cases do
          member do
            post :run, to: 'test_cases#run'
          end
        end
      end
    end
    

    我推荐的另一种方式

    resources :exercises, shallow: true do
      resources :questions do
        resources :test_cases do
          member do
            post :run
            get :test
          end
        end
      end
    end
    

    【讨论】:

    • 优秀,@Swards。有效!这些是我的 testshow 路线:test_cases_test GET /test_cases/test(.:format)test_case GET /test_cases/:id(.:format)。只是为了理解(这似乎是一个愚蠢的问题,但这条路线问题有时会让我感到困惑):看看这些路线,当你说它们具有相同的模式时,这里的“相同”到底是什么?
    • 如果您在控制台中执行rake routes,您可以看到匹配的模式。对于 test_case 路径,:id 是一个参数,可以是任何东西。因此,在这种情况下,“GET /test_case/”将到达test_cases#show,而“GET /test_case/test”将到达test_case#test。限制性更强的路由应该放在路由文件的首位。路由主要用于两件事 - 生成 url 字符串并将 url 请求匹配到控制器#actions。它按照路由文件的顺序匹配。是匹配的部分吸引了您,生成的 URL 按预期工作。
    • @rwehresmann - 为答案添加了另一个选项,可能更适合您的情况
    • 感谢您的解释!关于另一个选项,我不想在成员块中添加我的 test 路由。如果我这样做,我会将test_case_id 添加到我的路线中,在我的特殊情况下,我不会将此 id 用于任何事情。
    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 2017-03-18
    • 2017-09-29
    • 2023-03-31
    • 2015-02-24
    • 2010-09-07
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多