2014-07-03 29 views
2

所以我構建了一個身份驗證方法,它充當控制器中其他方法的before過濾器。基本上,如果用戶未登錄,我希望方法重定向到根路徑。以下是我的authenticate_user!前過濾方法:Rails控制器方法在Ajax調用後不重新載入頁面

def authenticate_user! 
     unless current_user 
     flash[:notice] = "Your session has ended. Please login again." 
     render js: "window.location.pathname = '#{root_path}'" 
     end 
end 

我遇到的問題是,窗口本身不重裝,而是在頁面中,並與文本內容元素顯示:「window.location.pathname =‘/’ 」。我無法使用redirect_to(我發現similar question here),因爲它似乎只是將某個內容元素髮送回root_path(而導航欄等元素保持不變)。這就是爲什麼我一直在尋找一個完整的窗口重新加載。任何幫助將非常感激。

編輯與服務器日誌

Started GET "/projects/editHeader?fileName=test.csv" for 127.0.0.1 at 2014-07-04 10:37:21 -0400 
Processing by ProjectsController#editHeader as TEXT 
    Parameters: {"fileName"=>"test.csv"} 
Filter chain halted as :authenticate_user! rendered or redirected 
Completed 200 OK in 2ms (Views: 0.1ms | ActiveRecord: 0.0ms) 


Started GET "/projects/headerDataPreview?fileId=NaN" for 127.0.0.1 at 2014-07-04 10:37:21 -0400 
Processing by ProjectsController#headerDataPreview as TEXT 
    Parameters: {"fileId"=>"NaN"} 
Filter chain halted as :authenticate_user! rendered or redirected 
Completed 200 OK in 1ms (Views: 0.1ms | ActiveRecord: 0.0ms) 

回答

2

你需要在的before_filter方法來指定請求類型

改變你的authenticate_user!方法

def authenticate_user 
    unless current_user 
    if request.xhr? # if its a ajax request then redirect with javascript 
     flash.keep[:notice] = 'Bla bla bla' # keeps the flash message for next request 
     render :js => "window.location = '#{root_path}'" 
    else 
     flash[:notice] = "Bla bla bla" 
     redirect_to root_path 
    end 
    end 
end 
+0

這個解決方案似乎沒有任何改變;它只是將屏幕帶到一個空白頁面,並顯示文本「window.location ='\'」。 –

+0

你可以發佈你的服務器日誌嗎?在我目前的項目中,我使用相同的代碼,它工作正常。 – Monideep

+0

當然,我已經更新了日誌。 –

0

首先,Ajax請求 - 將js放入控制器是個不好的做法。不要將客戶端腳本與服務器處理的控制器混合使關於你的問題 - 爲什麼你不使用rails重定向?

def authenticate_user! 
    unless current_user 
    redirect_to root_path, :notice => "Your session has ended. Please login again." 
    end 
end 
+0

redirect_to的問題在於整個屏幕沒有改變 - 只有內部內容元素。因此,即使我希望用戶在沒有導航欄的情況下進入登錄啓動頁面,導航欄仍會保留在屏幕上。 –

相關問題