开发者

How to use session[:user.return_to] from DEVISE

I'm trying to use session[:user.return_to] but with no success...

My code:

def after_sign_in_path_for(resource)
  (session[:"user.return_to"].nil?) ? "/" : session[:"user.return_to"].to_s
end

So, the problem is: When I check my session vari开发者_Go百科ables, I don't have any with those names.

I would like to get to the page I was working on, right before being redirected to the login page.


Struggling with the same problem. I have a so-so solution so far like so..

In my application_controller.rb

  before_filter :set_page # at the top and then

  protected
  def set_page
    unless request.referer.include?('/users/sign')
      session[:return_to] = request.referer
    end
  end

The unless statement is to prevent the user from being returned to the sign in or sign out page. I don't like that the url is hardcoded in here, so I'd like to see a better solution. Also it seems that before_filter never happens on a page which is redirected to the login page, so if you click something that requires sign in, after sign in you will be taken back to the page from where you clicked the link, not the actual link itself.


There are several ways you can go about this.

With the new version of Devise (I'm on 2.1.2), adding before_filter :authenticate_user! to your controller will automatically setup this behavior for you.

If you still want to manually set this up, one way is to just set the path in the session. Devise expects to find it in session["#{resource}_return_to"] where 'resource' is the name of your user model. So normally that is session["user_return_to"]. You had a period '.' in your version, which could have been causing your errors. Also, the session accepts string values for keys, so no need to try to symbolize it.

Another way is to overwrite the after_sign_in_path_for(resource) method as you were doing. There are more details on how to do this on the devise wiki How To: Redirect back to current page after sign in.

Lastly, since this will issue a redirect, you might want to consider using full URLs.

def after_sign_in_path_for(resource)
  session["#{resource}_return_to"] || root_url
end


in your ApplicationController.rb

 def after_sign_in_path_for(resource)
   sign_in_url = url_for(:action => 'new', :controller => 'sessions', :only_path => false, :protocol => 'http')
   if request.referer == sign_in_url
     super
   else
     stored_location_for(resource) || request.referer || root_path
   end
 end

stored_location_for(resource) is a built-in method from Devise that stores the locations from which the user was coming from.


You need to define the session variable before you redirect someone.

session[:url_back] = "/***


This could help http://ykyuen.wordpress.com/2011/03/10/rails-redirect-previous-page-after-devise-sign-in/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜