简体   繁体   中英

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM