Search code examples
ruby-on-railsruby-on-rails-4surveyor-gem

Implementation of survey using surveyor gem in rails


I am trying to implement a survey using the surveyor gem in rails. I want to make use of the user id to keep track of which user creates the survey and which user gave what response on which survey.

The problem is that I did not use the Devise gem for my user signin and signup. I built it manually. The surveyor gem uses a helper method current_user of Devise which returns details about the current user.

Since, I did not use devise, I am not sure where to add the helper method current_user.

I am not really sure as to what code to post, so please comment the required details. I will edit my post as needed.

Thanks!

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

Here is the link of the surveyor gem controller which uses the current_user method: https://github.com/kjayma/surveyor_gui/blob/master/app/controllers/surveyor_gui/survey_controller.rb


Solution

  • Here is one possible solution to implement a current_user method.

    helper_method would make the current_user method available in every controller, which inherits from ApplicationController.

    class ApplicationController
    
      helper_method :current_user
    
      def current_user
        @current_user ||= User.find(session[:user_id]) if session[:user_id]
      end
    end