Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Devise gem in Ruby on rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 466
    Comment on it

    Devise gem is one of the highly recommended gem used in Ruby on Rails.
    It has many features such as Email sending, locking User, Authenticating user and many more.

     

    To install Devise gem, you need to specify it in your Gemfile

    gem 'devise'

     

    Now, as we know to run any gem we have to run a command

    bundle install

    After Installing it in your Rails application, we are going to Integrate it.

    the first thing to do is to generate Devise configurations,

    rails g devise:install  // we can use g instead of generate, both gives same result

    when we run the above command it automatically create two files

        create  config/initializers/devise.rb
        create  config/locales/devise.en.yml

     

    Now, we are going to generate a Model for devise

    rails g devise User // User is the name of model and users will going to be Our table in Database

     

    the above command will create migration and model as well as routes for users

    create    db/migrate/20160511101503_devise_create_users.rb
    create    app/models/user.rb
    invoke    test_unit
    create      test/models/user_test.rb
    create      test/fixtures/users.yml
    insert    app/models/user.rb
    route  devise_for :users

     

    First we have migration, db/migrate/20160511101503_devise_create_users.rb

    class DeviseCreateUsers < ActiveRecord::Migration
      def change
        create_table(:users) do |t|
    
            t.string :name    // Manually Included
          ## Database authenticatable
          t.string :email,              null: false, default: ""
          t.string :encrypted_password, null: false, default: ""
    
          ## Recoverable
          t.string   :reset_password_token
          t.datetime :reset_password_sent_at
    
          ## Rememberable
          t.datetime :remember_created_at
    
          ## Trackable
          t.integer  :sign_in_count, default: 0, null: false
          t.datetime :current_sign_in_at
          t.datetime :last_sign_in_at
          t.inet     :current_sign_in_ip
          t.inet     :last_sign_in_ip
    
          ## Confirmable
          t.string   :confirmation_token
          t.datetime :confirmed_at
          t.datetime :confirmation_sent_at
          t.string   :unconfirmed_email # Only if using reconfirmable
    
          ## Lockable
          t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
          t.string   :unlock_token # Only if unlock strategy is :email or :both
          t.datetime :locked_at
    
    
          t.timestamps
        end
    
        add_index :users, :email,                unique: true
        add_index :users, :reset_password_token, unique: true
        add_index :users, :confirmation_token,   unique: true
        add_index :users, :unlock_token,         unique: true
      end
    end

    In migration file uncomment everything, because we are going to need everything. Except the headings

    we have included one extra fields in our migration, this will going to include in the users table, when we migrate our database.


    Now we have app/models/user.rb file,

    class User < ActiveRecord::Base
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
    end

    It consists of various methods

    1. database_authenticatable: This method will authenticate user, It checks whether the User is present in our database or not.
    2. registrable: This method gives the privilege to user to get signup and can update or delete their profile too.
    3. recoverable: when User could not able to login and want to reset their password, then this method comes into play.
    4. rememberable: It stores your credentials in the browser cookie, when next time you try to login it just fill your credentials automatically.
    5. trackable: It keeps track, that how many time you logged in, from which IP address and the Time of login
    6. validatable: This method checks whether the email is in correct format or not, whether your password is upto the characters you have set. you can customize it.
    7. confirmable: If you want to confirm that user had provided the correct email or not, then this method is used.
    8. lockable: It lock-out the user if the number of unsuccessful attempts exceeds.

    Now, we have enough interaction with model and migration, We are going to run it.

    rake db:migrate

    this command will create a table in your database named as users.

    CREATE TABLE users
    (
      id serial NOT NULL,
      name character varying,
      email character varying NOT NULL DEFAULT ''::character varying,
      encrypted_password character varying NOT NULL DEFAULT ''::character varying,
      reset_password_token character varying,
      reset_password_sent_at timestamp without time zone,
      remember_created_at timestamp without time zone,
      sign_in_count integer NOT NULL DEFAULT 0,
      current_sign_in_at timestamp without time zone,
      last_sign_in_at timestamp without time zone,
      current_sign_in_ip inet,
      last_sign_in_ip inet,
      confirmation_token character varying,
      confirmed_at timestamp without time zone,
      confirmation_sent_at timestamp without time zone,
      unconfirmed_email character varying,
      failed_attempts integer NOT NULL DEFAULT 0,
      unlock_token character varying,
      locked_at timestamp without time zone,
      created_at timestamp without time zone,
      updated_at timestamp without time zone
    )

    We are going to generate views for the devise.

    rails g devise:views users

    Devise give you the privilege to generate views for the particular method.

    for example

    rails g devise:views -v mailer registrations

    As we have generated views for devise, we can also generate its controllers.

    create  app/controllers/users/confirmations_controller.rb
    create  app/controllers/users/passwords_controller.rb
    create  app/controllers/users/registrations_controller.rb
    create  app/controllers/users/sessions_controller.rb
    create  app/controllers/users/unlocks_controller.rb
    create  app/controllers/users/omniauth_callbacks_controller.rb

    It will create all its controllers and when we open it.

    we found that Devise controller is inherited by every controller created by us.

    class Users::ConfirmationsController < Devise::ConfirmationsController

    It also defines the methods, which inherits the methods of super class.

     

    # GET /resource/confirmation/new
      # def new
      #   super
      # end

    If you want to customize devise controller it can be done here.

    As Views are created, we have to include the name field into that.

    In views/devise/registrations/new.html.erb

    <h2>Sign up</h2>
    
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= devise_error_messages! %>
    
      <%#-----------add this----------%>
      <div class="field">
        <%= f.label :name %><br />
        <%= f.text_field :name, autofocus: true %>
      </div>
    
      <div class="field">
        <%= f.label :email %><br />
        <%= f.email_field :email, autofocus: true %>
      </div>
    
      .......................
      .......................
      <div class="actions">
        <%= f.submit "Sign up" %>
      </div>
    <% end %>

    and in views/devise/registrations/edit.html.erb

    <h2>Edit <%= resource_name.to_s.humanize %></h2>
    
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
      <%= devise_error_messages! %>
    
      <%#-----------add this----------%>
      <div class="field">
        <%= f.label :name %><br />
        <%= f.text_field :name, autofocus: true %>
      </div>
    
      <div class="field">
        <%= f.label :email %><br />
        <%= f.email_field :email, autofocus: true %>
      </div>
    
      <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
        <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
      <% end %>
    
      ........................
      ........................
    <% end %>

    As we have added our field

    We have to do a last change in application_controller.rb

    class ApplicationController < ActionController::Base
    
      protect_from_forgery with: :exception
    
        # --------------add the lines below----------
        before_action :configure_permitted_parameters, if: :devise_controller?
          def configure_permitted_parameters
          devise_parameter_sanitizer.for(:account_update) << :name
        end
    
    end

    The above lines will fetch the value of name field in edit form.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: