Rails Devise only redirects to a fixed path. Need to redirect back where the user came from when authentication was triggered
Working on a Ruby on Rails app with Devise.
Devise only redirects to a fixed path, root app path by default. There are protected urls, and if the user click some links (e.g. "Ask Question" here), he i开发者_如何学运维s sent to the /sign_in page. On successful logon, the user is not sent back to the "Ask Question", but rather to "/". Any idea how to fix that?
This is what I am using. It works ;)
class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(resource)
if resource.is_a?(User)
"/welcome"
else
super
end
end
end
You have to save the url on your session hash for it to work.
session[:return_to] ||= request.referer
Then redirect to it in your update action, after a successful save:
redirect_to session[:return_to]
Makinng the original request GET instead of POST resolved the issue. It was initially wrong to redirect to POST. Unfortuntely if the user was trying to update any data he will be forced to re-enter and re-submit, the solution here is to disallow users to enter any data which they will not be able to submit if they are not logged in.
To redirect users back to the page they were on when they clicked the Sign In link, I use:
class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(resource)
:back
end
end
Try with this method in your application_controller.rb
def after_sign_in_path_for(resource)
(session[:"user.return_to"].nil?) ? "/" : session[:"user.return_to"].to_s
end
精彩评论