【问题标题】:Why is Rails 3.2.2 Generating URLs prefixed with /assets when using redirect_to?为什么 Rails 3.2.2 在使用 redirect_to 时会生成前缀为 /assets 的 URL?
【发布时间】:2023-03-11 18:00:02
【问题描述】:

好吧,标题问题几乎总结了它,但我还是想详细说明一个场景,

我创建了一个 DemoController,(我还没有创建 Resource 模型),我的 routes.rb 看起来像这样:

DispatchMe::Application.routes.draw do
  root to: "demo#index"
end

在演示控制器中,我做了以下操作:

class DemoController < ApplicationController
  def index
    redirect_to :action => 'show'
  end

  def show
  end
end

当然有一个文件:app/views/demo/show.html.erb,而且我希望该模板能够被渲染,但我得到了以下错误:

ActionController::RoutingError(没有路由匹配 [GET] "/assets")

并且这个 URL 是作为重定向的结果生成的:

/assets?action=show&controller=demo

我在这里错过了一些东西吗?我认为 rails 应该为这种情况渲染动作模板。

注意。我知道如果我创建像 get 'show' => "demo#show" 这样的路线并调用 redirect_to show_path 它会正常工作,但我需要知道如果这是强制性的?

非常感谢!

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    对于所需的行为,使用render 而不是redirect_to

    class PagesController < ApplicationController
      def index
        render :action => "show"
      end
    
      def show
      end
    end
    

    编辑:

    您可以在其他操作上使用redirect_to,但据我所知,索引操作设置了基本路径。要简化路由定义,请使用resources :controller_name。您可以在命令行输入rake routes查看资源生成的路由。

    示例:

    demo_controller.rb

    class DemoController < ApplicationController
      def index
      end
    
      def show
        redirect_to :action => 'index'
      end
    end
    

    routes.rb

    DispatchMe::Application.routes.draw do
      root to: "demo#index"
      resources :demo
    end
    

    development.log

    Started GET "/demo/show" for 127.0.0.1 at 2012-04-04 14:55:25 -0400
    Processing by DemoController#show as HTML
      Parameters: {"id"=>"show"}
    Redirected to http://dispatch.dev/
    Completed 302 Found in 0ms (ActiveRecord: 0.0ms)
    

    【讨论】:

    • 是的,我自己也开始意识到这一点。但是对我来说,rails 不允许在没有路由定义的情况下使用 redirect_to 似乎几乎是不可接受的。 render 有效,但不会更新当前 URL,这不是这种情况下所需的行为。我希望在 RoR 方面有丰富经验的人可以向我解释为什么目前这样工作。
    • @user766388 我已经更新了我的答案。如果您需要代码示例,请告诉我。
    • 很好,你的解释好多了。但既然你提出来,我不能错过举个例子的机会。我真的很想看看。非常感谢。
    • 感谢您的示例和提供的所有帮助,先生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多