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

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

Before I begin with this tutorial, you must know about basic devise installation and usage. If you don't, you can go to this very simple step-by-step tutorial.

Just follow these steps;

1. Main page route, controller and view

config/route.rb

get '/main_page', to: 'main#index'



app/controllers/main_controller.rb

class MainController < ApplicationController
    def index
    end
end


app/views/main/index.html.erb

<h1>Ajax Login Example</h1>
<%= render partial: 'sign_in' %>


2. Based on view above, we need to create partial view file

app/views/main/_sign_in.html.erb

<%= form_for(resource, as: resource_name, url: session_path(resource_name), html: {id: 'sign_in_user', :'data-type' => 'json'}, remote: true) do |f| %>

    <div><%= f.label :email %><br />
        <%= f.email_field :email, autofocus: true %>
    </div>
    <div><%= f.label :password %><br />
        <%= f.password_field :password, autocomplete: "off" %></div>

    <% if devise_mapping.rememberable? -%>
 <div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
    <% end -%>

    <div><%= f.submit "Log in" %></div>
<% end %>



3. Devise configuration

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

config.http_authenticatable_on_xhr = true



4. Modify routes.rb

config/routes.rb

devise_for:users, controllers: {sessions: 'session'}



5. SessionController

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


app/controllers/session_controller.rb

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



6. Javascript

app/assets/js/application.js

$(document).ready(function(){
    $("form#sign_in_user")
    .on("ajax:success", function(event, xhr, settings) {
        //do_something
    });
});









Share: