2010-11-20 78 views
0

我正在開發一個Rails的Facebook應用程序。一些(不是全部)頁面需要用戶登錄;如果沒有,他們被重定向到「登錄」頁面。我不能使用redirect_to這個,因爲重定向需要通過Javascript完成(因爲它重定向父框架);此外,重定向需要知道最初請求的頁面的地址(回來),所以我不能只是重定向到將做重定向的虛擬頁面。Javascript redirect_to in rails

我試過使用佈局和render來實現這一點,但原始視圖仍然運行(雖然不產生);由於視圖需要只有在用戶登錄時才存在的變量,這會產生錯誤,導致腳本崩潰。

是否可以渲染布局但停止執行視圖?有沒有更好的方法來完成這一點?

+0

你試過渲染:text =>「」嗎? – Bohdan 2010-11-21 14:19:27

+0

渲染:文本完美的作品,謝謝! – error792 2010-11-27 04:16:26

回答

0

你可以把你的邏輯放在application_controller中before_filter調用的方法中,並檢查是否需要重定向?喜歡的東西:

class ApplicationController < ActionController::Base 
    before_filter :authenticate_user! 

    def authenticate_user! 
     if (authentication_required? && !user_authenticated?) 
      render :js => "[some javascript here]" and return 
     end 
    end 

    def authentication_required? 
     # logic to determine if auth is needed 
    end 

    def user_authenticated? 
     # logic to determine if user is authenticated 
    end 
end 

渲染:JS => ...應該讓你渲染,你需要返回到原始請求頁面的任何值的JavaScript(或可以使其他一些文件或任意文本)。