问题
My website allows users to browse freely up to the point where they need to be signed in to continue using the service (hitting the "sign up" button and going through the registration process).
Once the users sign up, I want to redirect them to the last interesting page they were browsing : it might be the page just before clicking the sign-up button, or something more complex. For instance suppose the user browses a "core" content page, then goes to the "about_us" page, then tries to sign up, I'd rather redirect those users to the "core" content page.
I am wondering what's the best way to do that
- Hidden params in forms ? Sounds annoying to keep track of this parameter all along the form (and keep it when there are errors, etc.)
- Session-based information (some kind of "smart-referrer" url)
- Page visits (eg. using Ahoy.js)
And where/when to do this "tracking" of the last relevant page ? In the controller ? in the view as JS code ?
Any tips to do something like this ?
回答1:
Both via hidden form fields and sessions have benefits. Using sessions in the controller would be the simplest for you to keep track of as far as development goes however if the user has multiple tabs open it could lead to an odd page flow if they jump between tabs. This is where hidden form fields work out a bit better but are more annoying to maintain. I tend to go with the sessions method and do something like the following in a controller action:
#This will store the page they're coming from to get to this action.
session[:interesting_page] = request.env["HTTP_REFERER"] || root_path
#Or store the current interesting page within the interesting page's controller action
session[:interesting_page] = request.original_url
回答2:
One way is simply to use HTTP_REFERER
to redirect on sign in. HTTP_REFERER
is of course limited since some clients do not send it. But you could also argue that if the client does not send the header they don't want to be tracked.
Another solution is to use the session:
class ApplicationController
after_action :set_referrer, unless: :user_signed_in?
def set_referrer
session[:referrer] = if request.post?
request.fullpath + '/new'
elsif request.patch? || request.put?
request.fullpath + '/edit'
else
request.fullpath
end
end
end
class SessionController
def create
@user = User.find_by(params[:email])
.try(:authenticate, params[:password])
if @user
render :new
else
redirect_to session[:referrer] || root_path
end
end
end
来源:https://stackoverflow.com/questions/43471501/navigation-based-redirections-after-sign-up