2017-01-04 54 views
0

在我的路線文件我有以下幾點:自定義路由重定向到錯誤的行動

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#test應該如何。 This question在不同情況下的問題大致相同。我不想遵循已接受的答案,因爲如果我將get 'test', to: 'test_cases#test'放在我的resources :test_casesmember塊之外,我將在我的路線中獲得question_id,並在member內阻止test_case_id。我不需要這些ID。

我可以選擇讓我想要的路線(test_cases/test)工作嗎?

回答

1

我認爲你在test_cases#show方法上是匹配的,因爲它與test_cases/test url具有相同的模式,並且它在之前。只要將test_cases/test獲取路線的路線的頂層文件

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 
+0

外觀極好,@Swards。有效!這些是我的'test'和'show'路由:'test_cases_test GET/test_cases/test(。:format)'和'test_case GET/test_cases /:id(。:format)''。只有理解(這可能看起來像一個愚蠢的問題,但這種路線問題有時會讓我困惑):看這些路線,當你說他們有相同的模式時,在這裏什麼是「相同的」? – rwehresmann

+1

如果在控制檯中執行'rake routes',則可以看到匹配的模式。對於test_case路徑,:id是一個參數,可以是任何東西。所以,在這種情況下,「GET/test_case/」將會到'test_cases#show',並且「GET/test_case/test」將會到'test_case#test'。路線文件中應該首先限制更多的路線。路由用於兩個主要的事情 - 生成url字符串並將url請求匹配到controller#操作。它按照路由文件的順序匹配。這是抓住你的匹配部分,生成的URL按預期工作。 – Swards

+0

@rwehresmann - 在答案中增加了另一個選項,可能更適合您的情況 – Swards