开发者

How to store which page non-signed in user arrived from in rails

开发者 https://www.devze.com 2023-04-01 10:36 出处:网络
(1) A \'Host\' share a link to a \'campaign\' on the site e.g. /campaigns/17 (2) The visitor to /campaigns/17 clicks on something that is only for signed in/signed up users and is taken to the sign i

(1) A 'Host' share a link to a 'campaign' on the site e.g. /campaigns/17

(2) The visitor to /campaigns/17 clicks on something that is only for signed in/signed up users and is taken to the sign in/sign up page

I'm trying to get the c开发者_JS百科ampaign id (e.g. 17) to be stored in the new user's paramaters (for which I was thinking of using a hidden field) but am not sure how to save the id. I have thought about request.path but don't know how to carry this through to the next page.


Here is how I solve this problem. I am assuming you have some type of authenticate method inside of your application controller.

Inside of your application controller, have something like the following:

def authenticate 
  unless current_user 
    session[:protected_destination] = request.fullpath
    flash[:notice] = "You're not logged in."
    redirect_to login_path
    return false
  end
end

Then, in your login logic, you must have some code like the following. For me, login happened in the UserSession controller since I use Authlogic.

def new
  session[:protected_destination] ||= request.referrer || root_path

  if current_user
    redirect_to session[:protected_destination]
    session[:protected_destination] = nil
  else
    @user_session = UserSession.new
  end
end

def create
  @user_session = UserSession.new(params[:user_session])

  if @user_session.save
    protected_destination = session[:protected_destination] || root_path
    session[:protected_destination] = nil
    redirect_to protected_destination
  else
    render :action => :new
  end
end

As you can see, the destination you want to go to is stored inside of the session. When you login, it checks if you were going somewhere, and then redirects you there if you were. If not, it will just take you to the root url.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号