Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to "redirect_to" in Ajax call?

The following attempt_login method is called using Ajax after a login form is submitted.

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 

The problem is that redirect_to doesn't work.

How would you solve this ?

like image 320
Misha Moroshko Avatar asked Mar 28 '11 04:03

Misha Moroshko


2 Answers

Finally, I just replaced

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

with this:

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

and it works fine!

like image 117
Misha Moroshko Avatar answered Sep 23 '22 00:09

Misha Moroshko


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 :)

like image 21
nathanvda Avatar answered Sep 22 '22 00:09

nathanvda