I'm building a RoR application that uses sever Ajax.Updater's that load partials into DIVs on the page. Unfortunately is the user's session expires it loads the contents of '/user/login' into the DIV that was updated by the Ajax.Updater. Furthermore, this login for doesn't work like the one at '/user/login' **What is the best way around this problem?** A valid answer would include some sample code or a link to some. Ideally the solution would happen on the Rails side of things, but if there is an elegant solution in the form of modify the prototype.js I would accept that as well.
People succeed in answering ParagramStudios's questions 26% of the time (9 successes in 34 attempts).
Answers by: Rich Collins
This is actually not that bad. You need to modify your redirect to login code. When the request is a XMLHttpRequest, you return javascript that will change the location to the login page. When it is not, then you use a normal redirect:
before_filter :redirect_unless_authenticated
def redirect_unless_authenticated
unless authenticated?
if request.xhr?
render :update do |page|
page.redirect_to :controller => 'login'
end
else
redirect_to :controller => 'login'
end
false #stop processing request
else
true #continue
end
end
Which file does this go in? I'm *very* new to rails.
Application.rb?
You would replace the action that is currently doing the redirect to /user/login with this code. Most likely application.rb.
Thanks Rich, I've got it working now (thanks to a colleugue who knows more rails). I just have one more question about your solution, how can I avoid seeing the redirect javascript that is loaded into the partial before the redirect takes effect? Right now you can see:
Try { window.location.href = "/user/login"; } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('window.location.href = \"/user/login\";'); throw e }
in the partial before the code moves you to /user/login. I'm using ajax updaters right now. Do I have to use ajax.request and process the response? I hope not.
Hmm it shouldn't load any visible code into the target. The javascript redirect is working? Let me know if you want to chat again and we can use campfire. Sorry that our chat "needs some work" :(
I hope you can get back to me about the question I asked in the comment above, but your code did lead the code we used to fix this problem so you win the cash. Thanks again.
I don't know the prototype library inside and out, but I think the fact that there is an :update specified means that it will load whatever response it gets into the target. If you remove the :update it would probably work. However, you would then have to use RJS to update the element instead of partial (a less than optimal choice). I think it would be hard to get that last bit done without digging into it myself.