ruby-on-railsauthenticationfilterruby-on-rails-5before-filter

Getting "Undefined method" when trying to create filter in a controller


I'm using Rails 5. In my application controller, I have:

private

def current_user
 @current_user ||= User.find_by(id: session[:user_id])
end

then, in another controller I have:

class MyObjectsController < ApplicationController

before_filter !current_user { redirect_to root_path }, except: [:search]

but I'm getting the error:

undefined method `current_user' for MyObjectsController:Class

What am I doing wrong and how can I apply a filter to every method in my controller except the search method?


Solution

  • The way you're using it, the current_user method is being called when the class is loaded, it won't be available at that level. It's only available during the request. This is what you probably meant.

    before_filter :require_current_user, except: [:search]
    
    def require_current_user
      redirect_to(:root, :notice => "you must be logged in") unless current_user
    end
    

    If you're using devise, you should be able to

    before_action :authenticate_user!, :except => [:search]