如何重定向到root - public/index.html?

gee*_*ter 26 redirect ruby-on-rails path root

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

def get_current_user
   @current_user = current_user
   if @current_user.nil?  
      redirect_to root_path
   end 
end
Run Code Online (Sandbox Code Playgroud)

我该如何实现这一目标?

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

 # root :to => "welcome#index"
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,说root_path未定义.

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

mea*_*gar 25

您可以通过将任何非空字符串作为: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 /
Run Code Online (Sandbox Code Playgroud)

假设你有一个public/index.html,这将是将要服务的.

  • @apneadiving这样做不仅仅意味着缺乏共享布局,而且没有任何问题.如果你打算提供一个静态索引文件,那么大概你已经确定*没有*一个共同的布局,并且绝对没有理由不以这种方式提供`index.html`. (7认同)

Rah*_*tel 8

在控制器上

 redirect_to root_path (will redirect to root '/')
Run Code Online (Sandbox Code Playgroud)


apn*_*ing 1

你想做的事情与 Rails 不兼容。

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

所以它的内部结构两者都需要。

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

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

然后设置:

root :to => "static#index"
Run Code Online (Sandbox Code Playgroud)

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

  • Rails 支持从“public”目录提供静态内容。这是完全“Rails 兼容”的。 (8认同)
  • 另外,“Rails 是 MVC,C 代表控制器,V 代表视图。因此其内部需要两者”也是完全错误的。每次执行 `redirect_to` 时,您都没有使用 MVC 中的“V”。 (7认同)
  • @apneadiving Rails 为每个新项目都提供了一个开箱即用的静态“public/index.html”,并且效果非常好。您不妨告诉他他**必须**接触数据库,否则他不会使用“MVC”中的“M”。 (4认同)