简体   繁体   中英

How to not apply before_filter for root route in rails?

I have a before_filter called check_login that looks something like this:

def check_login
  if not session[:user_id]
    flash[:error] = "Please log in to continue"
    redirect_to login_path
  end
end

I then put this before_filter in my application controller, and then exclude it in my login controller (with skip_before_filter :check_login )

The problem is that when the user hits the homepage for the first time (ie just localhost:3000), it will redirect them to the login page with the flash[:error] message displaying. However, for the homepage, I just want to show the login form. What's the cleanest way to handle this 'special-case'? I thought about putting the skip_before_filter in the controller that handles the homepage, but I didn't think this was very DRY, since if I change the homepage in the routes file, I'll have to also change the location of the skip_before_filter .

Thanks!

You can add some action in your filter

class LoginController < ApplicationController
  skip_before_filter :check_login, :only => [:login]

  def login
  end
end

And in Application Controller, "blank?" check on presence and nil. It useful

def check_login
  if session[:user_id].blank?
    flash[:error] = "Please log in to continue"
    redirect_to login_path
  end
end

You can add named action for your homepage:

class StaticPagesController < ApplicationController

  def home
  end
end

And then check the current action in your callback:

def check_login
  if not session[:user_id]
    flash[:error] = "Please log in to continue" unless params[:action] == "home"
    redirect_to login_path
  end
end

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