Rails do not use condition with before_filter

I am using before_filter in my application. Do I have a logged_in? 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 user controller, I want the action to be performed only if the user is not logged in. For this, I want to use a condition other than logged_in? method in before_filter like:

 before_filter :!(logged_in?) 

But that gives me an error. I cannot create a new method for logging in.

Please help me figure out the correct syntax for this.

+6
source share
3 answers

You can pass the before_filter block:

 before_filter { |c| !c.logged_in? } 

But this would not do anything, since the return value from the before filter will not go anywhere. If you want to perform an action if the user is not logged in, you must put this action in the before_filter file.

For example, if the action was redirected to the login page, path, you can do this:

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

This is long enough to justify its own method:

 before_filter :login_required def login_required redirect_to login_path unless logged_in? end 
+8
source

Although the accepted answer seems to work, I would do it differently.

 before_filter :login_required, unless: :logged_in? def login_required redirect_to login_path, notice: 'Please login' end 

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

+18
source

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 
0
source

Source: https://habr.com/ru/post/924444/


All Articles