Topic: redirect_to :back unless....

Hi:

I am trying to figure out how I can get this:
def create
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      flash[:notice] = "Successfully logged in."
      redirect_to :back
    else
      render :action => 'new'
    end
  end

to work so if the user is at the login screen, and logs in, it will be redirected root_url. Right now after the user logs in it just sits at the login screen. I want the redirect :back to work on other sections, but not @ login.

Thanks in advance.

Re: redirect_to :back unless....

redirect_to :back sends you back to the page that issued the request. The page that issued the POST to the create action is your login page, so it just redisplays that. This is how it is supposed to work, although it is perhaps not the most intuitive smile

To get the effect you want you can create something like this in your application controller (this is from the Authlogic Example App):

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end
    
def require_user
  unless current_user
    store_location
    flash[:notice] = "You must be logged in to access this page"
    redirect_to new_user_session_url
    return false
  end
end

def require_no_user
  if current_user
    store_location
    flash[:notice] = "You must be logged out to access this page"
    redirect_to account_url
    return false
  end
end

def store_location
  session[:return_to] = request.request_uri
end
    
def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
  session[:return_to] = nil
end

Then you use redirect_back_or_default instead of redirect_to :back. The before_filters require_user and require_no_user stores the location you want to redirect back to.