Rails 3: 如何在 Ajax 调用中“ redirect_to”?

在提交登录表单之后,使用 Ajax 调用以下 attempt_login方法。

class AccessController < ApplicationController
[...]
def attempt_login
authorized_user = User.authenticate(params[:username], params[:password])


if authorized_user
session[:user_id] = authorized_user.id
session[:username] = authorized_user.username
flash[:notice] = "Hello #{authorized_user.name}."
redirect_to(:controller => 'jobs', :action => 'index')
else
[...]
end
end
end

问题是 redirect_to不起作用。

你会怎么解决这个问题?

62825 次浏览

In one of my apps, i use JSON to carry on the redirect and flash message data. It would look something like this:

class AccessController < ApplicationController
...
def attempt_login
...
if authorized_user
if request.xhr?
render :json => {
:location => url_for(:controller => 'jobs', :action => 'index'),
:flash => {:notice => "Hello #{authorized_user.name}."}
}
else
redirect_to(:controller => 'jobs', :action => 'index')
end
else
# Render login screen with 422 error code
render :login, :status => :unprocessable_entity
end
end
end

And simple jQuery example would be:

$.ajax({
...
type: 'json',
success: functon(data) {
data = $.parseJSON(data);
if (data.location) {
window.location.href = data.location;
}
if (data.flash && data.flash.notice) {
// Maybe display flash message, etc.
}
},
error: function() {
// If login fails, sending 422 error code sends you here.
}
})

Finally, I just replaced

redirect_to(:controller => 'jobs', :action => 'index')

with this:

render :js => "window.location = '/jobs/index'"

and it works fine!

I think this is slightly nicer:

render js: "window.location.pathname='#{jobs_path}'"

def redirect_to(options = {}, response_status = {})
super(options, response_status)
if request.xhr?
# empty to prevent render duplication exception
self.status = nil
self.response_body = nil
path = location
self.location = nil


render :js => "window.location = #{path.to_json}"
end
end

There is very easy way to keep the flash for the next request. In your controller do something like

flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"

The flash.keep will make sure the flash is kept for the next request. So when the root_path is rendered, it will show the given flash message. Rails is awesome :)

Combining the best of all answers:

...
if request.xhr?
flash[:notice] = "Hello #{authorized_user.name}."
flash.keep(:notice) # Keep flash notice around for the redirect.
render :js => "window.location = #{jobs_path.to_json}"
else
...

I didn't want to modify my controller actions so I came up with this hack:

class ApplicationController < ActionController::Base
def redirect_to options = {}, response_status = {}
super


if request.xhr?
self.status        = 200
self.response_body = "<html><body><script>window.location.replace('#{location}')</script></body></html>"
end
end
end