loading...

Adding Devise to Ruby on Rails with one line of code

markmead profile image Mark ・2 min read

If you don't know what Devise is, then take a look at the repo on GitHub, but in short it's a way of authentication users that come to your Rails app.

Starting a new project

You can skip this step if you already have a Rails project setup that you want to add Devise too.

rails new devise-one-liner -C -T -S -B

Don't forget to cd into your project once complete

Adding Devise

Run this command in your terminal.

rails app:template LOCATION='https://railsbytes.com/script/X8Bsjx'

What this will do can be seen on the Authentication with Devise RailsBytes page, but let's break it down:

  • Add Devise gem

Terminal command adding Devise gem through bundle

  • Run bundle
  • Run the Devise install generator

Terminal running the Devise install generator

  • Ask for the name of you Devise model (in the example I use "user")

Terminal asking what's the name of the Devise model

  • Ask if you want extra attributes

Terminal if I want extra attributes for Devise

  • If you do want extra attributes it will ask you for theme

Terminal asking what extra attributes I want for Devise

  • Run the Devise generator for the model name you passed in (includes any extra attributes you've added)

Terminal running Devise install on the model name I passed in

Next steps

If this project is a customer-facing app then you definitely want to run through the manual setup Devise prints to the terminal, as this is just a testing project for me, I won't be doing that.

Run rails db:migrate if you haven't already, then fire up the Rails server and head on over the sign_up path (found at <model-name>/sign_up).

πŸŽ‰ Success πŸŽ‰
Devise sign up page with no CSS

But wait?! Where's first_name, last_name, and type?
To see these, you'd need to run rails g devise:views which will create the view files of Devise allowing you to edit them.

To show them on the sign_up page I'll edit devise/views/registrations/new and include the first_name and last_name fields.

Adding first_name and last_name fields to Devise sign up form

Don't forget to update Devise's permitted params so users can pass through the extra attributes, in my case first_name and last_name when signing up.

Here's an example from an app I was building

Allowing first_name and last_name params in Devise

Extra help

Posted on Jun 26 by:

markmead profile

Mark

@markmead

Building websites πŸ”¨

Discussion

markdown guide