Skip to content

Instantly share code, notes, and snippets.

@nkpgardose
Last active September 27, 2015 02:40
Show Gist options
  • Save nkpgardose/76473ee78d02a995116c to your computer and use it in GitHub Desktop.
Save nkpgardose/76473ee78d02a995116c to your computer and use it in GitHub Desktop.
Simple answer/s to every question you search
Simple answer/s to every question you search

Devise model

Generate devise model

$ rails generate devise user

Check user.rb, add or remove devise modules

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
end

Once add or remove, remove or uncomment devise migration correspond to devise modules of User

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## 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.string   :current_sign_in_ip
      t.string   :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 null: false
    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

Migrate

$ rake db:migrate

Devise strong parameters

If views and model is avaialable, generate controller for the devise model i.e. User

$ rails generate devise:controllers users
      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
===============================================================================

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

  Ensure you have overridden routes for generated controllers in your routes.rb.
  For example:

    Rails.application.routes.draw do
      devise_for :users, controllers: {
        sessions: 'users/sessions'
      }
    end

===============================================================================

Follow instruction given.

Strong Parameters

When you customize your own views, you may end up adding new attributes to forms. Rails 4 moved the parameter sanitization from the model to the controller, causing Devise to handle this concern at the controller as well. There are just three actions in Devise that allow any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and the permitted parameters by default are:

  • sign_in (Devise::SessionsController#create) - Permits only the authentication keys (like email)
  • sign_up (Devise::RegistrationsController#create) - Permits authentication keys plus password and password_confirmation
  • account_update (Devise::RegistrationsController#update) - Permits authentication keys plus password, password_confirmation and current_password

source: https://github.com/plataformatec/devise#strong-parameters

Only for user additional field for strong params

For example will be adding new field username

$ rails generate migration add_username_to_users username:string:uniq
$ rake db:migrate

On model adds the validation

class User < ActiveRecord::Base
  ...
  validates :username, presence: true, length: { maximum: 20 }
end

On user view e.i. in app/views/users/registrations/new.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
  <div class="field">
    <%= f.label :username %><br />
    <%= f.text_field :username, autofocus: true %>
  </div>
  
  ...
  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

Doing a test run, it will prompt you username cannot be blank because username do not have permit. To add username to the permit

class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :configured_permitted_parameters

  protected

  def configured_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :username
    devise_parameter_sanitizer.for(:account_update) << :username
  end
end

Add a before_filter :configured_permitted_parameters that add username to sign up and account_update

Devise views

$ rails generate devise:views users

Modify devise.rb

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  config.scoped_views = true

Done.

Devise

Simple answer/s to every question you search

How to install

  1. Add to your Gemfile.rb
gem 'devise'
  1. Run the Generator
$ rails generate devise:install
  1. It will prompt instruction, As of devise-3.5.2, do the follwing

development.rb

  Rails.application.configure do
     ...
     config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  end

production.rb

Rails.application.configure do
 ...
 config.action_mailer.default_url_options = { host: 'http://sample_host.com' }
end

routes.rb

  # Sample root route
  root to: "home#index"

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

$ rails g devise:views
      invoke  Devise::Generators::SharedViewsGenerator
       exist    app/views/devise/shared
      create    app/views/devise/shared/_links.html.erb
      invoke  form_for
       exist    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
       exist    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
       exist    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
       exist    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
       exist    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb
      invoke  erb
       exist    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment