2011-10-25 94 views
5

可以將自定義邏輯放在routes.rb中嗎?Rails路由邏輯

例如:

unless current_user 
    root :to => anonymous_page 
else 
    root :to => logged_in_page 
end 

回答

2

可以將自定義邏輯放入路由中......但是如復仇者建議的 - 「current_user」將不起作用,因爲何時加載路由文件。我們有時在我們的路線文件中使用邏輯(例如,建立僅在RAILS_ENV =='開發'時可用的路線)。

你可能想什麼是「anonymous_page」如的before_filter:

before_filter :redirect_if_logged_in, :only => :anonymous_page 

def redirect_if_logged_in 
    redirect_to logged_in_page if current_user.present? 
end 
2

這並不喜歡這項工作。在服務器啓動時讀取/創建路由,而不是基於每個請求。您必須將這種邏輯放入控制器中。

+0

注意:該設計在這裏做一些神奇的事情發生在這裏:https://github.com/plataformatec/devise/wiki/How-To:-Define-a-different-root-route-for-logged-in-出用戶 – Jonathan

0

可以使用間隙寶石做你在想什麼。從清關文件:

Blog::Application.routes.draw do 
    constraints Clearance::Constraints::SignedIn.new { |user| user.admin? } do 
    root to: 'admin' 
    end 

    constraints Clearance::Constraints::SignedIn.new do 
    root to: 'dashboard' 
    end 

    constraints Clearance::Constraints::SignedOut.new do 
    root to: 'marketing' 
    end 
end 

這工作,因爲間隙增加自己進入中間件堆棧,地位使簽署的處理路線可用之前。