2012-01-17 16 views
8

我正在使用Rails 3和Devise來創建一個應用程序,用戶到達網站並顯示一個包含登錄和註冊表單的主頁。這個頁面有其自己的控制器(「主頁」),所以它的路線是Rails 3 w/Devise:如何根據用戶是否通過認證來設置兩個獨立的主頁?

root :to => "homepage#index" 

我想,如果用戶已經登錄來顯示不同的主頁。這將帳戶具有根點

root :to => "dashboard#index" 

有沒有辦法在routes.rb中有條件路由,這將允許我檢查用戶是否在路由到這些主頁之一之前進行身份驗證?

我嘗試使用下面的代碼,但如果我沒有登錄,設計問我登錄,所以只有第一條路線的工作原理。

authenticate :user do 
    root :to => "dashboard#index" 
end 
    root :to => "homepage#index" 

而且,我想要的網址指向www.example.com在這兩種情況下,使www.example.com/dashboard/index和www.example.com/homepage/index從來沒有出現在瀏覽器。

非常感謝!

回答

13

試試這個,這是專門針對督導員/設計雖然。

root to: "dashboard#index", constraints: lambda { |r| r.env["warden"].authenticate? } 
root to: "homepage#index" 
+0

非常感謝@Bradley,這是在殺我:) – 2012-01-17 01:25:36

+0

我這樣做,但都登錄用戶和未登錄用戶使用儀表板#索引 – 2012-02-18 08:16:18

+1

警告:這不適用於Rails 4,你會得到一個錯誤:'無效的路由名稱,已經在使用:'root'' – Happynoff 2013-08-05 17:15:25

5

在你的HomeController:

def index 
    if !user_signed_in? 
    redirect_to :controller=>'dashboard', :action => 'index' 
    end 
end 
+0

感謝您的回覆@negarnil。事情是,我試過這個選項,但它不會重寫URL。我希望www.example.com指向這兩個頁面,以避免www.example.com/dashboard/index顯示 – 2012-01-17 00:47:06

+0

嘗試render:action =>'dashboard.html.erb。 http://guides.rubyonrails.org/layouts_and_rendering.html#wrapping-it-up – 2012-01-17 01:20:41

2

(完全相同的回答過的問題在這裏:https://stackoverflow.com/a/16233831/930038這裏添加答案太他人的參考。)

在你routes.rb

authenticated do 
    root :to => 'dashboard#index' 
end 

root :to => 'homepage#index' 

這將確保root_url所有認證用戶是dashboard#index

供您參考:https://github.com/plataformatec/devise/pull/1147

+0

在Rails 4中這不起作用。您必須重命名兩條路線中的一條。看我的[回覆](http://stackoverflow.com/a/19090936/1836143)。 – 2013-09-30 09:38:06

2

這裏的正確答案與軌道4

root to: 'dashboard#index', constraints: -> (r) { r.env["warden"].authenticate? }, 
     as: :authenticated_root 
root to: 'homepage#index' 

我試圖把它添加到/編輯接受的答案,但它是太多的編輯將要接受明顯。無論如何,投票接受的答案(來自布拉德利),它幫助我拿出這一個:)

相關問題