Devise Authenticate User for AJAX Requests
What is the best way of handling redirects in an AJAX call that require users (through devise)? I wanted to do something like:
$('#love').click(开发者_高级运维function() {
$.get('/item/#{item.id}', function(data) {
if (data.redirect) { window.location.replace(data.redirect); return; }
});
});
However, I'm not sure how to get devise before filter (authenticate user) handle the 'js' request format. Any ideas?
Devise has special option just for that: http_authenticatable_on_xhr
You might find this devise issue relevant.
Also, I really advice against using redirects with XHR requests. You'll find yourself in a world of pain once you try using that with firefox. Before Gecko 7.0 firefox wouldn't save headers from original request when following an XHR redirect.
According to developer.mozilla.org XMLHttpRequest page:
From Gecko 7.0 headers set by setRequestHeader() are sent with the request when following a redirect. Previously these headers would not be sent.
You can do something like this in your ApplicationController
file to redirect via AJAX:
# allows redirecting for AJAX calls as well as normal calls
def redirect_to(options = {}, response_status = {})
if request.xhr?
render(:update) {|page| page.redirect_to(options)}
else
super(options, response_status)
end
end
So essentially, if a request is made via AJAX and the controller action (or a before_filter) says to redirect to a sign in page, this will redirect the page for that AJAX call.
If you store the request data in a cookie, you might be able to fulfill the request after the user is properly authenticated.
精彩评论