Skip to content
This repository has been archived by the owner on Jun 13, 2023. It is now read-only.

Rails 4 tutorial

Richard Cook edited this page Mar 18, 2014 · 3 revisions

Overview

This document provides step-by-step instructions describing how to build a Rails 4.0.2 app from scratch incorporating user authentication using Devise and user impersonation via the user_impersonate2 gem. Note that there is not (yet) a separate tutorial for adding Devise and user_impersonate2 to a Rails 3.2.x application, but the steps are more or less the same as those presented here.

Related materials:

0. Create the application

rails _4.0.2_ new sample-app

1. Generate home controller

rails generate controller home

2. Create index action for home controller

  • Add app/views/home/index.html.erb
  • Add route to config/routes.rb

3. Add Devise gem

  • Add gem to Gemfile:
gem 'devise'
  • Run Bundler to update the app:
bundle
  • Generate Devise initializers etc.
rails generate devise:install
  • Add settings to config/environments/development.rb:
  config.action_mailer.default_url_options = { :host => 'localhost:3000' }
  • Add Devise links and flash to app/views/layouts/application.html.erb:
  <% if user_signed_in? %>
    <%= link_to "Edit profile (#{current_user.email})", edit_user_registration_path %>
    <%= link_to 'Sign out', destroy_user_session_path, :method => :delete %>
  <% end %>

  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  • Generate Devise views
rails generate devise:views
  • Generate User model
rails generate devise User
  • Migrate the database
rake db:migrate

4. Create access-controlled Note model

  • Generate Note model and scaffold:
 rails generate scaffold note user_id:integer text:string

5. Add authentication to all controllers

  • Add filter to app/controllers/application_controller.rb:
  before_filter :authenticate_user!

6. Add belongs_to relationship to User

  • In CreateNotes migration, change t.integer :user_id to t.belongs_to :user

  • Add relationship to Note:

  belongs_to :user
  • Add relationship to User:
  has_many :notes
  • Migrate the database
rake db:migrate

7. Add user_impersonate2 gem

  • Add gem to Gemfile:
gem 'user_impersonate2', :require => 'user_impersonate'
  • Run Bundler to update the app:
bundle
  • Generate initializer:
rails generate user_impersonate

8. Add impersonation header and link

  • Modify app/views/layout/application.html.erb:
  <% if current_staff_user %>
    <%= render 'user_impersonate/header' %>
  <% end %>
  • Modify app/views/home/index.html.erb:
  <% if current_user.staff? %>
    <li><%= link_to 'Impersonate', '/impersonate' %></li>
  <% end %>

9. Add staff concept to User model

  • Add staff column to database:
rails generate migration add_staff_to_users staff:boolean
rake db:migrate
  • Add to_s to User class:
  def to_s
    email
  end