Swati Aggarwal
Swati Aggarwal

Reputation: 1275

Rails use not condition with before_filter

I'm using before_filter in my application. I have a method logged_in? which returns true if the user is logged in.

def logged_in?
  !!current_user
end

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

Now in my users controller I want an action to execute only if a user is not logged in. For this I want to use the not condition with logged_in? method in before_filter as:

before_filter :!(logged_in?)

But this gives me an error. I'm resisting creating a new method for not logged in.

Please help me figure out the correct syntax to accomplish this.

Upvotes: 6

Views: 11890

Answers (3)

vipin
vipin

Reputation: 2510

application_controller.rb

before_filter :authorize

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

protected
def authorize
   unless User.find_by(id: session[:user_id])
     redirect_to login_url, :notice => "Not Authorize Member"
   end
end

Upvotes: 0

Jason Noble
Jason Noble

Reputation: 3766

While the accepted answer seems to work, I would have done it differently.

before_filter :login_required, unless: :logged_in?

def login_required
  redirect_to login_path, notice: 'Please login'
end

This will execute the method login_required unless the user is already logged in. See http://robots.thoughtbot.com/post/159805303/before-filter-wisdom for more info.

Upvotes: 18

Chris Salzberg
Chris Salzberg

Reputation: 27374

You could pass a block to before_filter:

before_filter { |c| !c.logged_in? }

But this wouldn't really do anything, since the return value from the before filter isn't going anywhere. If you want to execute an action if a user is not logged in, then you should be putting that action into the before_filter.

For example, if the action was to redirect to the login page, path, you could do this:

before_filter { |c| redirect_to login_path unless c.logged_in? }

That's actually long enough to justify a method of its own:

before_filter :login_required

def login_required
  redirect_to login_path unless logged_in?
end

Upvotes: 8

Related Questions