2011-06-06 32 views
17

我希望在應用程序/公用文件夾中對index.html進行重定向。如何重定向到root - public/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?

+4

而不是使用'root_path',使用'redirect_to'/'' – meagar 2011-06-06 20:19:51

+0

@meagar這是答案,而不是評論,那麼爲什麼不直接創建答案而不是評論問題呢? – MBO 2011-06-06 20:21:46

+1

@MBO這不是一個答案。問題是「我該如何做X?」而我的評論是「不要,反而是Y」。這不是一個可以接受的答案IMO,我會低估其他人張貼它。 – meagar 2011-06-06 20:23:14

回答

5

你想要做的不是Rails兼容。

Rails是MVC,C是控制器,V是視圖。

所以它的內部需要兩個。

好的,public/index.html默認顯示,但它只是因爲過程被繞過。

因此,您可以創建一個static控制器,其中有一個index動作和相應的視圖(只需複製/粘貼當前的public/index.html文件的內容)。

然後設置:

root :to => "static#index" 

並請,刪除public/index.html文件:

+7

Rails支持從'public'目錄提供靜態內容。這完全是「Rails兼容」。 – meagar 2011-06-06 20:20:49

+3

@apneadiving Rails爲每個新項目提供了一個靜態的'public/index.html'開箱即用,並且工作得很好。你可能會告訴他他必須**觸摸數據庫,否則他不會在'MVC'中使用'M'。 – meagar 2011-06-06 20:24:31

+7

另外「Rails是MVC,C是控制器,V是視圖,所以它的內部需要兩個」是完全錯誤的。每次你做'redirect_to'你都沒有在MVC中使用「V」。 – meagar 2011-06-06 20:27:05

19

你可以通過任何非空字符串作爲: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,這是將是SER VED。

+0

這樣做也意味着所提供的視圖與應用程序中的其他視圖無關,這實際上不太可能。視圖有一個共同的佈局,這就是Rails DRYness的美麗。 – apneadiving 2011-06-06 20:39:29

+7

@apneadiving這樣做意味着不僅僅是缺少共享佈局,而是沒有錯。如果你打算提供一個靜態索引文件,那麼大概你已經決定了*沒有*一個共同的佈局,並且絕對沒有理由不以這種方式提供'index.html'。 – meagar 2011-06-06 20:40:51

+1

@meagar完全。實際上,IMO是_shared layout_(MVC)和_quick response_(靜態文件)之間的一種選擇。 Rails支持Rails的靈活性。 (在MVC的情況下,我仍然可以使用CSS來保持一個共享的外觀。) – 2015-12-21 05:49:53

3

路由文件:

 root 'main#index' 

控制器:

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

和使用Rails 4控制器動作住這可以使用M &下用在V

扭表現得像一個單頁的應用
+0

你甚至不需要定義'def index'動作。只定義控制器和索引文件就足夠了。如果找不到,Rails將跳過路由中的操作。 – LessQuesar 2017-04-03 14:22:40

6

控制器上

redirect_to root_path (will redirect to root '/') 
相關問題