2015-11-26 22 views
0

我正在嘗試使用rails中的surveyor gem進行調查。我想利用用戶ID來跟蹤哪個用戶創建調查,以及哪個用戶在哪個調查中給出了什麼響應。在軌道上使用Surveyor gem進行調查的實施

問題是我沒有使用設計寶石用於我的用戶登錄和註冊。我手動建立它。 Surveyor gem使用Devise的helper方法current_user來返回有關當前用戶的詳細信息。

因爲,我沒有使用設計,我不知道在哪裏添加輔助方法current_user。

我不太確定要發佈什麼代碼,因此請評論所需的詳細信息。我將根據需要編輯我的帖子。

謝謝!

application_controller.rb

class ApplicationController < ActionController::Base 
# Prevent CSRF attacks by raising an exception. 
# For APIs, you may want to use :null_session instead. 
protect_from_forgery with: :exception 
before_filter :authorize 
helper_method :current_user 
protected 
    def authorize 
    return true if ((self.class == SessionsController)|| (self.class == UsersController && (self.action_name == "new" || self.action_name == "create"))) 
    unless (User.find_by_id(session[:user_id])) 
     redirect_to url_for(:controller => :sessions , :action => :new), alert: "You need to be logged in." 
    end 
    end 

def current_user 
    @current_user = User.find(session[:user_id]) 
end 
end 

這裏是其使用方法CURRENT_USER測量員寶石控制器的鏈接:https://github.com/kjayma/surveyor_gui/blob/master/app/controllers/surveyor_gui/survey_controller.rb

+0

有什麼好運氣? –

回答

0

這裏是實施current_user方法的一個可能的解決方案。

helper_method會使current_user方法可用於每個控制器,從ApplicationController繼承。

class ApplicationController 

    helper_method :current_user 

    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 
end 
+0

我做到了。我在Application控制器的protected方法下添加了current_user方法。但是這種方法沒有被使用。這我知道,因爲我故意拼錯User.find()User.kind(),它仍然顯示沒有錯誤。任何想法可能是什麼問題?我正在編輯我的問題以提供應用程序控制器。我確實在進行調查之前確認用戶已經登錄。因此,在這種情況下,會話[:user_id]永遠不能爲空。 –

+0

將它添加到'before_filter',以便設置它:'before_filter:current_user' –

+0

謝謝!有用! :) –