Skip to content

Instantly share code, notes, and snippets.

@withoutwax
Last active April 27, 2024 00:43
Show Gist options
  • Save withoutwax/46a05861aa4750384df971b641170407 to your computer and use it in GitHub Desktop.
Save withoutwax/46a05861aa4750384df971b641170407 to your computer and use it in GitHub Desktop.
Adding Custom Fields to Devise

Adding Custom Fields to Devise

Before doing anything, please check the versions of the gem files:

gem 'rails', '~> 5.1.4'
gem 'devise', '~> 4.4.0'

Disclaimer - This solution may not work with older versions of rails and devise. Versions listed above were the latest versions of gems which I was using at the time of creation and tests. (10 Jan 2018)

Step 01: Install & Generate Devise

If you do not know the install process, please visit Getting Started part of Devise README.md

Step 02: Change code in devise.rb

In order to visually see all the new fields and alterations of login, sign up etc pages, we need to first change the following code in: config/initializers/devise.rb

config.scoped_views = true

Step 03: Generate a migration file for model created with Devise

bash

$ rails generate migration add_name_to_users name:string

Step 04: Check Migration file

_db/migrate/....add_name_to_users.rb

class AddNameToUsers < ActiveRecord: :Migration
     def change
          add_column :users, :name, :string
     end
end

Step 05: Migrate Database

bash

$ rake: db:migrate

Step 06: Update code in ApplicationController

Similar to permitting parameters, we need to create permitting parameters to devise model as well.
app/controllers/application_controller.rb

class ApplicationController < ActionController: :Base
     protect_from_forgery with: :exception

     before_action :configure_permitted_parameters, if: :devise_controller?

     protected

          def configure_permitted_parameters
               devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:name, :email, :password)}

               devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:name, :email, :password, :current_password)}
          end

end

Step 07: Register & Edit Users with custom fields

Add new custom fields inside html.erb files. app/views/layout/index.html.erb

<%= link_to 'Edit Profile', edit_user_registration_path %>

app/views/users(or devise)/registrations/new.html.erb

<div>
     <%= f.label :name %><br />
     <%= f.text_field :name, autofocus: true %>
</div>

app/views/users(or devise)/registrations/edit.html.erb

<div>
     <%= f.label :name %><br />
     <%= f.text_field :name, autofocus: true %>
</div>
@flstudio4
Copy link

You are a life saver, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment