2015-11-26 20 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

谢谢!有用! :) –