Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise with rails 3 and remote => true

I have a problem using devise with an AJAX login. I'm using the :remote => true option and the jQuery version of the javascript helpers (https://github.com/rails/jquery-ujs). Ehen the user enters the correct informations, my create.js.erb inside the sessions view is rendered. This is ok, 'cause i can redirect my user using JS in this file. But when an error occurs, e.g. the user enters false information, only the flash messages are in the response with an error code 401 - Unauthorized. So, no view or create.js.erb or sth else is rendered. But I want to handle this message, by displaying it on the side, so that the users gets some feedback, whats wrong.

I also tried to implement my own custom controller with respond_to :js, and playing with the :recall method of the warden authentication. But it doesn't work.

Does anybody know some best practices to solve this problem? Or should I avoid this helper methods and just use pure jQuery for the ajax calls?

thx, tux

like image 283
23tux Avatar asked Mar 28 '11 14:03

23tux


People also ask

What is Rails devise?

Devise is an excellent authentication system made for Rails that allows us to easily drop-in User functionality into our project. Devise only includes an email and password for registration, let's also add our own username to our User model. We also want to have a unique index on our username.

What is devise warden?

The devise gem is basically based on a warden gem, which gives an opportunity to build authorization direct on a Ruby Rack Stack. This gem is pretty straightforward and well documented. Warden fetches a request data and checks if the request includes valid credentials, according to a defined strategy.


2 Answers

You could use the jQuery event "ajax:error" in rails 3. Just bind the event to your form.

jQuery(function($) {
  $("#new_model").bind("ajax:error", function(event, data, status, xhr) {
    alert("something went wrong");
  });
});

Take a look at this blog post for more details on what events are available.

like image 80
Braden Becker Avatar answered Oct 06 '22 00:10

Braden Becker


Here's my version

<script>
  $(document).ajaxError(function(e, XHR, options){
    if (XHR.status == 401){
      window.location.replace("<%= new_user_session_path %>");
    }
  });
</script>

It automatically redirects the user to the login page and works for all elements on the page.

like image 38
montrealmike Avatar answered Oct 05 '22 22:10

montrealmike