How to create ajax-signup in Ruby-on-Rails and Devise

Ruby on Rails, 2015-06-17 00:10:48 UTC

This is a continuation of the previous tutorial in Ruby on Rails about signing-in a user with ajax.
http://www.develbook.com/2015/03/how-to-create-ajax-login-in-ruby-on.html

Now, I want to show you how to create the devise signing-up in Ruby-on-Rails in the very short tutorial.

1. In the devise-ajax sign-up, the most important thing considered is the parameters passed via ajax form. Whatever form you create, make sure you have an input attribute name for your form is something like user[field].

Ajax code;

$.ajax({
    url: '/users',
    type: 'POST',
    data: 'authenticity_token='+$('meta[name=csrf-token]').attr('content')
        +'&user[email]='+$('#user_email').val(),
        +'&user[password]='$('#user_password').val(),
        +'&user[password_confirmation]='+$('#user_password_confirmation').val(),
    success: function(response) {
        //do something if success
    }
});



2. Devise configuration

Find line below in config/initializers/devise.rb and uncomment

config.http_authenticatable_on_xhr = false



3. Modify routes.rb

config/routes.rb

devise_for:users, controllers: {registrations: 'registration'}



4. RegistrationController

rails g controller Registration --no-helper --no-assets --no-views


app/controllers/registration_controller.rb

class RegistrationController < Devise::SessionsController
    respond_to :html, :json
end



That's it! Very easy. :)


Share: