Adding Authentication with Devise
Created by Piotr Steininger, @polishprince
Updated by Ernesto Jimenez, @ernesto_jimenez
This guide assumes that you have already built a Rails Girls app by following the app development guide.
1. Add devise gem
Open up your
Gemfile and add this line
to install the gem. Also remember to restart the Rails server.
2. Set up devise in your app
Run the following command in the terminal.
3. Configure Devise
Ensure you have defined default url options in your environments files. Open up
config/environments/development.rb and add this line:
app/views/layouts/application.html.erb and add:
app/views/ideas/show.html.erb and remove the line that says:
Do the same for
app/views/comments/show.html.erb. These lines are not necessary as we’ve put the notice in the
4. Setup the User model
We’ll use a bundled generator script to create the User model.
Coach: Explain what user model has been generated. What are the fields?
5. Create your first user
Now that you have set everything up you can create your first user. Devise creates all the code and routes required to create accounts, log in, log out, etc.
Make sure your rails server is running, open http://localhost:3000/users/sign_up and create your user account.
6. Add sign-up and login links
All we need to do now is to add appropriate links or notice about the user being logged in in the top right corner of the navigation bar.
In order to do that, edit
Finally, force the user to redirect to the login page if the user was not logged in. Open up
app/controllers/application_controller.rb and add:
class ApplicationController < ActionController::Base.
Open your browser and try logging in and out from.
Coach: Talk about the
current_user helpers. Why are they useful?
- Add extra fields to the User model
- Add relationships between users and ideas
- Restrict users to only be able to edit their own ideas and delete their own comments
- Expand to use roles or permissions (use one of the popular authorization gem like CanCan)
- Handy cheatsheet for Ruby, Rails, console etc.
- Guide 1: Guide to install Rails
- Guide 2: Build Your First App
- Guide 3: Push Your App to GitHub
- Guide 4: Put your app online with…
- Guide 5: Allow Comments on Your App
- Guide 6: Add design using HTML & CSS
- Guide 7: Create thumbnails with Carrierwave
- Guide 8: Add Authentication (user accounts) with Devise (Current page!)
- Guide 9: Add Profile Pics with Gravatar
- Guide 10: Improve your design with HTML and CSS
- Guide 11: Continuous Deployment
- Guide 12: Build a voting app in Sinatra
- Guide 13: Build a diary app in Ruby on Rails
- Guide 14: Add a back-end to your app (admin pages)
- Guide 15: Go through additional explanations for the App