2015-11-18 94 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'在我给的例子中工作? –