【问题标题】:How do I redirect to root - public/index.html?如何重定向到 root - public/index.html?
【发布时间】:2011-09-09 14:11:35
【问题描述】:

我希望重定向到我的应用程序/公共文件夹中的 index.html。

def get_current_user
   @current_user = current_user
   if @current_user.nil?  
      redirect_to root_path
   end 
end

我如何做到这一点?

我还没有修改我的 routes.rb 中的根(它仍然被评论)

 # root :to => "welcome#index"

我收到一条错误消息,提示 root_path 未定义。

如何修改 routes.rb 让 root_path 指向 public/index.html ?

【问题讨论】:

  • 不要使用root_path,而是使用redirect_to '/'
  • @meagar 这是答案,不是评论,那你为什么不直接创建答案而不是评论问题呢?
  • @MBO 这不是一个答案。问题是“我该如何做 X?”我的评论是“不要,而是做 Y”。这不是 IMO 可接受的答案,我会否决其他人这样发布它。

标签: ruby-on-rails path redirect root


【解决方案1】:

您想要做的与 Rails 不兼容。

Rails 是 MVC,C 代表控制器,V 代表视图。

所以它的内部需要两者。

好的,默认显示public/index.html,但这只是因为绕过了进程。

因此,您可以创建一个带有index 操作的static 控制器及其对应的视图(只需将当前public/index.htmlfile 的内容复制/粘贴到其中即可)。

然后设置:

root :to => "static#index"

请删除public/index.html 文件:)

【讨论】:

  • Rails 支持从public 目录提供静态内容。这完全“兼容 Rails”。
  • @apneadiving Rails 为每个新项目都提供了一个开箱即用的静态public/index.html,它运行良好。您不妨告诉他他必须触摸数据库,否则他没有使用“MVC”中的“M”。
  • 另外“Rails 是 MVC,C 是控制器,V 是视图。所以它的内部需要两者”是完全错误的。每次您执行 redirect_to 时,您都没有在 MVC 中使用“V”。
  • @meagar 我是 Rails 的新手(和一般的 MVC),所以你能解释一下为什么 redirect_to 意味着我们没有使用 'V' 吗?我不明白。如果这需要一个新问题来获得长答案,请告诉我,我会创建它!
  • @Lucas 当您从控制器的操作中调用 redirect_to 时,不涉及 View
【解决方案2】:

您可以通过将任何非空字符串作为:controller 并将文件的路径作为路由的:action 传递给静态文件:

Application.routes.draw do

  root :controller => 'static', :action => '/' 
  # or
  # root :controller => 'static', :action => '/public/index.html'

end

# elsewhere

redirect_to root_path # redirect to /

假设您有一个public/index.html,这就是将提供的内容。

【讨论】:

  • 这样做也意味着所服务的视图与应用程序中的其他视图无关,这确实不太可能。视图有一个共同的布局,这就是 Rails DRYness 的美妙之处。
  • @apneadiving 这样做不仅仅意味着缺少共享布局,但这并没有错。如果您打算提供静态索引文件,那么大概您已经决定不是通用布局,并且绝对没有理由不以这种方式提供index.html
  • @meagar 完全。实际上,IMO 它是 shared layout (MVC) 和 quick response (static files) 之间的选择。 Rails 支持这两者,Rails 的灵活性之美。 (在 MVC 情况下,我仍然可以使用 CSS 来保持某种共享外观。)
【解决方案3】:

路由文件:

     root 'main#index'

控制器:

     class MainController < ApplicationController
       def index
         redirect_to '/index.html'
       end
     end

使用 rails 4 控制器动作,这可以表现得像一个使用 M&C 的单页应用程序,并在 V 上进行扭曲

【讨论】:

  • 您实际上甚至不需要定义def index 操作。只定义控制器和索引文件就足够了。如果找不到,Rails 将跳过路由中的操作。
【解决方案4】:

在控制器上

 redirect_to root_path ## (will redirect to root '/')

【讨论】:

    【解决方案5】:

    routes.rb

    ...
    root to: redirect('public/index.html')
    ...
    

    这会将所有请求重定向到'/''public/index.html'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2011-05-30
      相关资源
      最近更新 更多