如何在没有路由帮助程序的情况下链接到操作



如何在没有路由帮助程序的情况下链接到操作?

我有一条路线

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

我得到

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

Routing from the Outside from the Outside"和"Getting Started with Rails",但我没有注意到任何有帮助的东西。

我可以将路由更改为

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

并依靠路由助手,但这感觉很黑客。

我正在使用 Rails 3.2.22。

我做错了什么?

路由需要更改为

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

我不明白的是,如果路由错误,为什么我首先能够查看带有http://localhost:3000/batches/521/creation_wizard/add_funds的页面。

4.x 版的 Rails 指南提到

对于命名空间控制器,可以使用目录表示法。为 例:

资源:user_permissions,控制器:"管理员/user_permissions"这个 将路由到 Admin::UserPermissions 控制器。

仅支持目录表示法。指定控制器 使用 Ruby 常量表示法(例如控制器:"管理员::用户权限"( 可能会导致路由问题并导致警告。

但不幸的是,在 Rails 指南的 3.2.x 版本的等效部分中似乎没有提到这一点。

这将修复它:

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

您遇到的问题是命名空间资源和嵌套资源之间的混淆。

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]}

嵌套资源允许您定义"顶级"级别信息(在本例中为 batch_id ,然后这些信息将向下渗透到被调用的控制器。路线看起来像url.com/batches/:batch_id/creation_wizard/add_funds

最新更新