0

我正在尝试使用 rails 中的surveyor gem 进行调查。我想使用用户 ID 来跟踪哪个用户创建了调查,以及哪个用户对哪个调查给出了什么回复。

问题是我没有使用 Devise gem 进行用户登录和注册。我手动构建它。测量员 gem 使用 Devise 的辅助方法 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 方法的测量员 gem 控制器的链接:https ://github.com/kjayma/surveyor_gui/blob/master/app/controllers/surveyor_gui/survey_controller.rb

4

1 回答 1

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
于 2015-11-26T21:38:13.703 回答