Add Devise GEM In RoR

March 21, 2015 - Rails

Steps To Use Devise Gem :-

1) You can add it to your Gemfile with:

          gem devise

Run the bundle command to install it.

2) After you install Devise and add it to your Gemfile, you need to run the generator:

         rails generate devise:install

The generator will install an initializer which describes ALL of Devise’s configuration options. It is imperative that you take a look at it. Look Console to do some code manually i.e.

Some setup you must do manually if you haven’t yet:

1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:

        config.action_mailer.default_url_options = { host: ‘localhost:3000’ }

In production, :host should be set to the actual host of your application.

2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:

        root to: “home#index”

3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:

       <p class=”notice”><%= notice %></p>
       <p class=”alert”><%= alert %></p>

4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

config.assets.initialize_on_precompile = false

On config/application.rb forcing your application to not access the DB
or load models when precompiling your assets.

5. You can copy Devise views (for customization) to your app by running:

      rails g devise:views

3) When you are done, you are ready to add Devise to any of your models using the generator:

      rails generate devise user

Replace MODEL with the class name used for the application’s users (it’s frequently user but could also be Admin). This will create a model (if one does not exist) and configure it with default Devise modules. The generator also configures your config/routes.rb file to point to the Devise controller.

4) Then Run :

      rake db:migrate

5) Now add Code to app/controllers/application_controller.rb :

      before_action :authenticate_user!

6) Now Run server By :-

      rails s 

It Works!!!

7) Now we Create Logout (Signout) in Devise Gem By :-

Put Code in app/views/layouts/application.html.erb :-

<ul class=”nav navbar-nav navbar-right”>
<% if user_signed_in? %>
<li class=”dropdown”>
<a href=”#” class=”dropdown-toggle” data-toggle=”dropdown”><%= %>&nbsp;<i class=”glyphicon glyphicon-user”></i>&nbsp; <b
<ul class=”dropdown-menu”>
<%= link_to ‘Edit profile’, edit_user_registration_path %>
<%= link_to “Logout”, destroy_user_session_path, method: :delete%>

<li class=”divider”></li>
<% else %>
<%= link_to “Sign up”, new_user_registration_path, :class => ‘navbar-link’
<%= link_to “Login”, new_user_session_path, :class => ‘navbar-link’ %>
<% end %>

-> Now Run Server By :-

       rails s

->Good Work Now Your Signup, Login (Signin), Logout (Signout), Work Fine Enjoy…!!!! 

Leave a Reply