2015-11-18 29 views
0

如何鏈接到沒有路線幫手的動作?如何鏈接到沒有路線幫手的動作

我有一個路線

get '/batches/:id/creation_wizard/add_funds' => 'batch::creation_wizard#add_funds' 

如果我在Rails的做控制檯

include Rails.application.routes.url_helpers 
default_url_options[:host] = "localhost" 
url_for(controller: 'batch::creation_wizard', action: 'add_funds', id: 1) 

我得到"http://localhost/batches/1/creation_wizard/add_funds"

但是,如果我有

class Batch::CreationWizardController < ApplicationController 
    def my_method 
    redirect_to controller: 'batch/creation_wizard', action: 'add_funds', id: 1 
    end 
end 

時I g等

No route matches {:controller=>"batch/batch::creation_wizard", :action=>"add_funds", :id=>1} 

如果我嘗試

redirect_to controller: 'creation_wizard', action: 'add_funds', id: 1 

我得到

No route matches {:controller=>"batch/creation_wizard", :action=>"add_funds", :id=>1} 

如果我嘗試

redirect_to action: 'add_funds', id: 1 

我得到

No route matches {:action=>"add_funds", :id=>1, :controller=>"batch/creation_wizard"} 

我嘗試閱讀Rails指南「從外部輸入的Rails路由」和「Rails入門」,但我沒有注意到任何幫助。

我可以在路由改變

get '/batches/:id/creation_wizard/add_funds' => 'batch::creation_wizard#add_funds', as: :creation_wizard_add_funds 

,並依靠在路線上的幫手,但那種感覺哈克。

我正在使用Rails 3.2.22。

我在做什麼錯?

回答

0

路線需要改變,以

get '/batches/:id/creation_wizard/add_funds' => 'batch/creation_wizard#add_funds' 

什麼我不明白,所以我能在第一時間與http://localhost:3000/batches/521/creation_wizard/add_funds查看的網頁如果路由是錯誤的。

Rails的用於指導4.x版本mentions

對於命名空間的控制器,可以使用目錄符號。對於 示例:

資源:user_permissions,controller:'admin/user_permissions'此 將路由到Admin :: UserPermissions控制器。

僅支持目錄表示法。用Ruby常數表示法(例如,控制器:'Admin :: UserPermissions') 指定控制器 可能導致路由問題並導致警告。

但不幸的是,似乎沒有在3.2.x版本的Rails指南中的equivalent section中提及。

0

這將解決這個問題:

class Batch::CreationWizardController < ApplicationController 
    def my_method 
    redirect_to controller: 'batch::creation_wizard', action: 'add_funds', id: 1 
    end 
end 

你的問題是namespacednested資源之間的混淆。

Namespacing是爲了給你一個模塊的功能(IE保持功能依賴於特定類型的資源,一定程度):

#config/routes.rb 
namespace :batch do 
    resources :creation_wizard do 
     get :add_funds, on: :member 
    end 
end 

這將創建下列路線:

{action: "show", controller:"batch::creation_wizard", id: "1"} 

命名空間基本上就是爲你提供一個文件夾來放置控制器。它最常用的功能admin,讓您使用的喜歡:

#config/routes.rb 
namespace :admin do 
    root "application#index" 
end 

#app/controllers/admin/application_controller.rb 
class Admin::ApplicationController < ActionController::Base 
    ... 
end 

這是你所擁有的目前。

-

如果你想(使用「頂級」的資源來影響「下位」資源IE)使用嵌套路線,你要你的路線更改爲以下:

#config/routes.rb 
resources :batches do 
    resources :creation_wizard do 
     get :add_funds, on: :member 
    end 
end 

這將提供以下路線:

{controller: "creation_wizard", action: "add_funds", batch_id: params[:batch_id]} 

嵌套資源允許你定義 「頂」 級信息(在T他的案例,batch_id,然後將滴流到被叫控制器。路線看起來像url.com/batches/:batch_id/creation_wizard/add_funds

+0

爲什麼'redirect_to action:'add_funds',id:1'在我給的例子中工作? –