Skip to content

Tutorial (Walkthrough)

Daniel Kehoe edited this page Mar 1, 2011 · 139 revisions

Rails3-Mongoid-Devise

This is a detailed tutorial showing how to use Mongoid with Devise. Mongoid is a datastore that gives you quick development without schemas or migrations. Devise gives you ready-made authentication and user management.

Help and More Information

To keep up to date with development of this app, follow me on Twitter:
http://twitter.com/yaxdotcom.

Any issues? Please create an Issue on GitHub.

Tutorial

This tutorial documents each step that you must follow to create this application. Every step is documented concisely, so a complete beginner can create this application without any additional knowledge. However, no explanation is offered for any of the steps, so if you are a beginner, you’re advised to look for an introduction to Rails elsewhere. Refer to the Rails Guides site for help if you are a beginner.

Creating the Application

Option One

Cut and paste the code.

To create the application, you can cut and paste the code from the tutorial into your own files. It’s a bit tedious and error-prone but you’ll have a good opportunity to examine the code closely.

Option Two

Use the ready-made application template to generate the code.

You can use an application template to generate a new Rails app with code that closely matches the tutorial. You’ll find an application template for this tutorial in the fortuity/rails3-application-templates repository.

Use the command:

$ rails new APP_NAME -m https://github.com/fortuity/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb -T -O -J

Use the -T -O -J flags to skip Test::Unit files, Active Record files, and Prototype files.

This creates a new Rails app (with the APP_NAME you provide) on your computer. It includes everything in the example app. You can read through the tutorial with the code already on your computer.

You MUST be using Rails 3.0.4 or newer. Generating a Rails application from an “HTTPS” URL does not work in Rails 3.0.3 and earlier versions.

Option Three

Create a custom application template to generate the code.

Each step in this tutorial has a corresponding application template recipe from the fortuity/rails-template-recipes project repository.

You can create your own application template from scratch using the template recipes. You can base your new application template on the file rails3-mongoid-devise-template.rb found at the project fortuity/rails3-application-templates, adding any recipes you desire.

Option Four

Use RailsWizard.org to create a custom application template.

You can use the RailsWizard.org web site to create your own custom application template (use the RailsWizard.org “Customize Template” option), adding any template recipes you want from the fortuity/rails-template-recipes project repository.

Use the RailsWizard graphical menu to select Mongoid, ERB or Haml, and a CSS framework. Do NOT select RSpec, Cucumber, jQuery, or Devise from the RailsWizard graphical menu (our own recipes are better than the RailsWizard stock recipes).

Add the following to the RailsWizard.org “Customize Template” section to create an application template to produce the code from this tutorial:

git_repo = "https://github.com/fortuity/rails-template-recipes"
@recipe_list = recipes ; def recipe_list; @recipe_list end
def extra_recipes; @extra_recipes end
@extra_recipes = %w{ git rspec cucumber jquery devise
  bson_ext mongoid_cleanup 
  action_mailer add_user_name 
  home_page home_page_users seed_database users_page 
  css_setup application_layout devise_navigation 
  cleanup ban_spiders }
@extra_recipes.each { |r| apply "#{git_repo}/raw/master/#{r}.rb" }

Be sure to use the -T -O -J flags to skip Test::Unit files, Active Record files, and Prototype files.

Assumptions

Before beginning this tutorial, you need to install

  • The Ruby language (version 1.8.7 or 1.9.2)
  • Rails (version 3.0.5)
  • A working installation of MongoDB (version 1.6.0 or newer)

I recommend installing rvm, the Ruby Version Manager, to manage multiple versions of Rails.

If you are using rvm, you can see a list of the Ruby versions currently installed:
$ rvm list

Check that appropriate versions of Ruby and Rails are installed in your development environment:
$ ruby -v
$ rails -v

If you don’t have MongoDB installed on your computer, you’ll need to install it and set it up to be always running on your computer (run at launch). On Mac OS X, the easiest way to install MongoDB is to install Homebrew and then run the following:

brew install mongo
sudo mkdir -p /data/db
sudo chmod -Rv 777 /data/

Create the Rails Application

Open a terminal, navigate to a folder where you have rights to create files, and type:

$ rails new rails3-mongoid-devise

You may give the app a different name if you are building it for your own use. For this tutorial, we’ll assume the name is “rails3-mongoid-devise.”

This will create a Rails application that uses a SQLite database for data storage. We’ll modify it to use MongoDB.

After you create the application, switch to its folder to continue work directly in that application:

$ cd rails3-mongoid-devise

Edit the README file to remove the standard Rails boilerplate. Add what you like (perhaps the name of your app?).

Set Up Source Control (Git)

If you are creating an application template, this step uses the git recipe from the fortuity/rails-template-recipes repository.

If you’re creating an app for deployment into production, you’ll want to set up a source control repository at this point. If you are building a throw-away app for your own education, you may skip this step.

Check that git is installed on your computer:

$ git version

Rails 3 has already created a .gitignore file for you. You may want to modify it:

.bundle
db/*.sqlite3
log/*.log
tmp/
.DS_Store

Initialize git and check in your first commit:

$ git init
$ git add .
$ git commit -am 'initial commit'

You can check your commit status at any time with:

$ git status

Save it to GitHub

Use a remote source control repository if you want an offsite copy of your work or you plan to share your work with others.

We’ll assume you have an account at GitHub. Check that your GitHub account is set up properly:

$ ssh git(at)github.com

Go to GitHub and create a new empty repository (http://github.com/repositories/new) into which you can push your local git repo.

Add GitHub as a remote repository for your project and push your local project to the remote repository:

$ git remote add origin git(at)github.com:YOUR_GITHUB_ACCOUNT/YOUR_PROJECT_NAME.git
$ git push origin master

At each stage of completion, you should check your code into your local repository:

$ git commit -am "some helpful comment"

and then push it to the remote repository:

$ git push origin master

Set Up Gems

About Required Gems

The application uses the following gems. I recommend checking for newer versions of these gems before proceeding:

The app has been tested with the indicated versions. If you are able to build the app with a newer gem, please create an issue on GitHub and I will update the app.

Set up Your Gemfile

Edit the Gemfile file to look like this:

source 'http://rubygems.org'

gem 'rails', '>= 3.0.5'
gem 'mongoid', '>= 2.0.0.rc.7'
gem 'bson_ext', '>= 1.2.4'
gem 'devise', '>= 1.2.rc'

Install the Required Gems

Install the required gems on your computer:

$ bundle install

You can check which gems are installed on your computer with:

$ gem list --local

Keep in mind that you have installed these gems locally. When you deploy the app to another server, the same gems (and versions) must be available.

Configuration for jQuery

An error in the RailsWizard recipe (as of 20 February 2011) will cause a failure if you select jQuery in the Javascript Framework section of the RailsWizard.org web application.

Instead, add the jquery recipe from the fortuity/rails-template-recipes repository. It substitutes for selecting jQuery in the Javascript Framework section of the RailsWizard.org web application.

This example application doesn’t make use of jQuery. But many Rails developers prefer it as an alternative to the Prototype Javascript framework so instructions are included here.

How to Manually Install jQuery

Here’s how to manually install jQuery.

Remove the Prototype Javascript files from the public/javascripts directory:

  • controls.js
  • dragdrop.js
  • effects.js
  • prototype.js

If you used the -J flag when you ran rails new the Prototype Javascript files won’t be there.

Download jQuery and rails.js and place them in the public/javascripts directory.

cd public/javascripts
curl -o rails.js https://github.com/rails/jquery-ujs/raw/master/src/rails.js
curl -o jquery.js http://code.jquery.com/jquery-1.5.min.js

Uncomment the following statement in the config/application.rb file (or add it if it is missing):

config.action_view.javascript_expansions[:defaults] = %w(jquery rails)

This configures the template helper javascript_include_tag :defaults to generate SCRIPT tags to load jQuery and the rails.js script.

How to Automatically Install jQuery

As an alternative to manual installation of jQuery, you can add a gem and run a generator command.

# Gemfile
gem 'jquery-rails', '>= 0.2.7'

Run the generator command (add --ui if you want the optional jQuery UI library):

$ bundle install
$ rails generate jquery:install

This will remove the Prototype files from the public/javascripts directory, download the latest jQuery files, and download the rails.js file. Be sure to choose to overwrite the rails.js file (or remove it first).

Configuration for Haml

You can select Haml in the Templating Engine section of the RailsWizard.org web application.

In this example, we’ll use the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml. You’ll need extra gems in the Gemfile for Haml:

gem 'haml', '>= 3.0.25'
gem 'haml-rails', '>= 0.3.4', :group => :development
# the folowing gems are used to generate Devise views for Haml
gem 'hpricot', '>= 0.8.3', :group => :development
gem 'ruby_parser', '>= 2.0.5', :group => :development

Run the gem bundler commnd:

$ bundle install

With the haml-rails gem, there is no need to modify the application.rb file to accommodate Haml. Any time you generate a controller or scaffold, you’ll get Haml instead of ERB templates. And when your Rails application loads, Haml will be loaded and initialized.

Adding RSpec for Unit Testing

If you are using RailsWizard, add the rspec recipe from the fortuity/rails-template-recipes repository. It substitutes for selecting RSpec in the Unit Testing Framework section of the RailsWizard.org web application.

You don’t have to install RSpec. The example app will run without it. However, if you are planning to use the example app as a starter app for futher development, you really should install RSpec. RSpec is generally preferred to the Rails default TestUnit for unit testing.

The RSpec Book is the best reference for using RSpec.

Use the gem rspec-rails to set up the app for RSpec.

Add the following to your Gemfile file:

gem 'rspec-rails', '>= 2.5', :group => [:development, :test]
gem 'database_cleaner', :group => :test

The gem rspec-rails needs to be in the :development group (as well as the :test group) to expose generators and rake tasks during development.

Install the required gems on your computer:

$ bundle install

Use the rspec-rails generator to set up files needed for RSpec:

$ rails generate rspec:install

Remove ActiveRecord artifacts

To use Mongoid with RSpec, you’ll need to remove ActiveRecord artifacts from the spec/spec_helper.rb file. Modify the file to comment out or remove:

# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# config.use_transactional_fixtures = true

Without this adjustment, when you run rake spec with spec files that contain require 'spec_helper' you’ll get an error undefined method `fixture_path='.

Database Cleaner for RSpec

RSpec needs to reset the database during testing. You’ll need to configure RSpec to inform Database Cleaner that you are using Mongoid.

Modify the file spec/spec_helper.rb to add this:

RSpec.configure do |config|
  # Other things

  # Clean up the database
  require 'database_cleaner'
  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.orm = "mongoid"
  end

  config.before(:each) do
    DatabaseCleaner.clean
  end
end

Run RSpec

Run rake -T to check that rake tasks for RSpec are available.

You should be able to run rake spec to run all specs. If you haven’t written any specs, you’ll see the message “No examples matching ./spec//_spec.rb could be found”.

You can copy the files from the example spec directory to use our ready-made specs.

Add Cucumber for Behavior Driven Development

If you are using RailsWizard, add the cucumber recipe from the fortuity/rails-template-recipes repository. It substitutes for selecting Cucumber in the Integration Testing Framework section of the RailsWizard.org web application.

It’s not necessary to add Cucumber (the example will run without it). However, it’s a recommended practice to specify use cases (“user stories”) as Cucumber scenarios. It’s a good way to plan development and, using Cucumber, you’ll have specifications for automated acceptance testing.

The RSpec Book covers Cucumber as well as RSpec. The free book The Secret Ninja Cucumber Scrolls is another good reference for using Cucumber.

Use the gem cucumber-rails to set up the app for Cucumber.

Add the following to your Gemfile file:

gem 'cucumber-rails', :group => :test
gem 'capybara', :group => :test
end

Install the required gems on your computer:

$ bundle install

Use the cucumber-rails generator to set up files needed for Cucumber:

$ rails generate cucumber:install --capybara --rspec --skip-database

The -–capybara option specifies Capybara instead of the default Webrat for acceptance testing. The -–rspec option enables RSpec matchers for your step definitions. If you used the -O flag when you generated the application, the --skip-database option will allow the Cucumber generator to proced without a database.yml file.

Database Cleaner for Cucumber

To reset your application database to a pristine state during testing, Cucumber makes use of Database Cleaner. You’ll need to configure Cucumber to inform Database Cleaner that you are using Mongoid.

Create a file features/support/local_env.rb like this:

require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.orm = "mongoid"
Before { DatabaseCleaner.clean }

Run Cucumber

Run rake -T to check that rake tasks for Cucumber are available.

You should be able to run rake cucumber (or more simply, cucumber) to run all Cucumber scenarios and steps. If you haven’t written any Cucumber scenarios and steps, you’ll see the message “0 scenarios, 0 steps”.

You can copy the files from the example features directory to use our ready-made Cucumber scenarios.

Use Mongoid

You can create an application template that uses Mongoid by selecting Mongoid in the Database/ORM section of the RailsWizard.org web application.

You’ll also need the bson_ext recipe from the fortuity/rails-template-recipes repository. It supplements the standard RailsWizard Mongoid installation.

This step adds the mongoid_cleanup recipe from the fortuity/rails-template-recipes repository.

Mongoid provides access to the MongoDB database from Rails.

You may want to check the current instructions for installing Mongoid.

Set up Mongoid with:

$ rails generate mongoid:config

You can use the default Mongoid configuration found in the file config/mongoid.yml.

The Mongoid generator automatically modifies the config/application.rb file to use Mongoid instead of the default ActiveRecord.

It will replace the line:

require 'rails/all'

with:

require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"

If you are using RSpec, you don’t need the following. Be sure to comment it out unless you are using the default Test::Unit.

# require "rails/test_unit/railtie"

Now you can safely remove the file config/database.yml.

Note that it is no longer necessary (as of 9 June 2010) to modify config/application.rb for Mongoid. The necessary changes to the Rails generators are handled by the Mongoid gem. When you generate a model, Rails will generate a Mongoid Document.

Test the App

You can check that your app runs properly by entering the command

$ rails server

To see your application in action, open a browser window and navigate to http://localhost:3000/. You should see the Rails default information page.

Stop the server with Control-C.

Configure ActionMailer

This step is the action_mailer recipe from the fortuity/rails-template-recipes repository.

In its default configuration, Devise sends email messages to confirm new users and reset passwords. You’ll want to configure ActionMailer to show errors during development and suppress failures when the app is deployed to production.

Set up action_mailer in your development environment in the file

config/environments/development.rb

by changing:

# Don't care if the mailer can't send
# config.action_mailer.raise_delivery_errors = false

and adding:

# ActionMailer Config
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# A dummy setup for development - no deliveries, but logged
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"

Set up action_mailer in your production environment in the file

config/environments/production.rb

by adding:

config.action_mailer.default_url_options = { :host => 'yourhost.com' }
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"

Set Up Authentication

Set Up Configuration for Devise

A typo in the RailsWizard recipe (as of 20 February 2011) will cause a failure if you select Devise in the Authentication System section of the RailsWizard.org web application.

Instead, add the devise recipe from the fortuity/rails-template-recipes repository. It substitutes for selecting Devise in the Authentication System section of the RailsWizard.org web application.

This app uses Devise for user management and authentication. Devise is at http://github.com/plataformatec/devise.

We’ve already installed the Devise gem with the $ bundle install command. Run the generator:

$ rails generate devise:install

which installs a configuration file:

config/initializers/devise.rb

and a localization file.

Devise will recognize that you already have Mongoid installed and it will set its ORM configuration in the config/initializers/devise.rb file to include:

require 'devise/orm/mongoid'

Generate a Model and Routes for Users

Devise can manage users and administrators separately, allowing two (or more) roles to be implemented differently. For this example, we just implement Users.

Use Devise to generate models and routes for a User:

$ rails generate devise User

Devise will recognize that Mongoid is installed and set up the User model with

include Mongoid::Document

which must precede all other statements in the model.

Devise will modify the config/routes.rb file to add:

devise_for :users

which provides a complete set of routes for user signup and login. If you run rake routes you can see the routes that this line of code creates.

Prevent Logging of Passwords

We don’t want passwords written to our log file. In Rails 2, we would change the file

controllers/application_controller.rb

to include:

filter_parameter_logging :password, :password_confirmation

In Rails 3, this is deprecated and instead we modify the file config/application.rb to include:

config.filter_parameters += [:password, :password_confirmation]

Note that filter_parameters is an array.

Customize the Application

Enable Users to Have Names

This step is the add_user_name recipe from the fortuity/rails-template-recipes repository.

By default, Devise uses an email address to identify users. We’ll add a “name” attribute as well.

We’re using Mongoid so there is no need to set up migration files as we would with MySQL or SQLite.

We’ll modify the user model to allow a “name” to be included when adding or updating a record.

You’ll also want to prevent malicious hackers from creating fake web forms that would allow changing of passwords through the mass-assignment operations of update_attributes(attrs) and new(attrs). With the default Rails ActiveRecord, Devise adds

attr_accessible :email, :password, :password_confirmation, :remember_me

You’ll need to add this yourself when using Mongoid.

Modify the file models/user.rb and add:

field :name
validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me

This will allow users to be created (or edited) with a name attribute. When a user is created, a name and email address must be present and must be unique (not used before). Note that Devise (by default) will check that the email address and password are not blank.

Create Customized Views for User Registration

Devise provides a controller and views for registering users. It is called the “registerable” module. The controller and views are hidden in the Devise gem so we don’t need to create anything. However, because we want our users to provide a name when registering, we will create custom views for creating and editing a user. Our custom views will override the Devise gem defaults.

If you are using Haml, you must have extra gems in the Gemfile to generate Devise views for Haml:

# the following gems are required to generate Devise views for Haml
gem 'hpricot', :group => :development
gem 'ruby_parser', :group => :development

First, to copy all the default Devise views to your application, run

rails generate devise:views

This will generate a set of views in the directory app/views/devise/.

Next, modify the views to create and edit users.

Add the following code to each file:

app/views/devise/registrations/edit.html.erb

  <p><%= f.label :name %><br />
  <%= f.text_field :name %></p>

app/views/devise/registrations/new.html.erb

  <p><%= f.label :name %><br />
  <%= f.text_field :name %></p>

We do not need to add a controller with methods to create a new user or edit or delete a user. We use the existing “registerable” module from Devise which provides a controller with methods to create, edit or delete a user.

Note that Devise’s default behaviour allows any logged-in user to edit or delete his or her own record (but no one else’s). When you access the edit page you are editing just your info, and not info of other users.

Create a Home Page

This step is the home_page recipe from the fortuity/rails-template-recipes repository.

Remove the Default Home Page

Delete the default home page from your application:

$ rm public/index.html

Create a Home Controller and View

Create the first page of the application. Use the Rails generate command to create a “home” controller and a “views/home/index” page.

$ rails generate controller home index

If you’re using the default template engine, you’ll find an erb file with placeholder content:

app/views/home/index.html.erb

If you’re using Haml, you’ll find a haml file with placeholder content:

app/views/home/index.html.haml

We’ll assume you’re using the default template engine for the remainder of this tutorial.

Now, you have to set a route to your home page. Edit the file config/routes.rb and replace:

get "home/index"

with

root :to => "home#index"

We’ll add some content to the home page in the next step.

Test the App

You can check that your app runs properly by entering the command

$ rails server

To see your application in action, open a browser window and navigate to http://localhost:3000/. You should see your new home page.

Stop the server with Control-C.

Create a Default User

Display Users on the Home Page

This step is the home_page_users recipe from the fortuity/rails-template-recipes repository.

Modify the file controllers/home_controller.rb and add:

def index
  @users = User.all
end

Modify the file app/views/home/index.html.erb and add:

<h3>Home</h3>
<% @users.each do |user| %>
  <p>User: <%= user.name %> </p>
<% end %>

Set Up a Database Seed File

This step is the seed_database recipe from the fortuity/rails-template-recipes repository.

You’ll want to set up a default user so you can test the app. Modify the file db/seeds.rb by adding:

puts 'EMPTY THE MONGODB DATABASE'
Mongoid.master.collections.reject { |c| c.name =~ /^system/}.each(&:drop)
puts 'SETTING UP DEFAULT USER LOGIN'
user = User.create! :name => 'First User', :email => 'user@test.com', :password => 'please', :password_confirmation => 'please'
puts 'New user created: ' << user.name

You can change the values for name, email, and password as you wish.

Seed the Database

Add the default user to the MongoDB database by running the command:

$ rake db:seed

Test the App

At this point, you may want to know if the default user has been saved to the MongoDB database.

You can check that your app runs properly by entering the command

$ rails server

To see your application in action, open a browser window and navigate to http://localhost:3000/. You should see your new home page.

Stop the server with Control-C.

Set Up a Demonstration of Devise

You’ll want to see how Devise manages authentication.

Set Up the Users Controller, Views, and Routes

This step is the users_page recipe from the fortuity/rails-template-recipes repository.

Use the Rails generate command to create a “users” controller and a “views/user/show” page.

$ rails generate controller users show

Note that “users” is plural when you create the controller.

Modify the file controllers/users_controller.rb and add:

before_filter :authenticate_user!

def show
  @user = User.find(params[:id])
end

The file config/routes.rb has already been modified to include:

get "users/show"

Remove that and change the routes to:

root :to => "home#index"
devise_for :users
resources :users, :only => :show

Important note: The devise_for :users route must be placed above resources :users, :only => :show.

Modify the file app/views/users/show.html.erb and add:

<p>User: <%= @user.name %></p>

Add Links to Users on the Home Page

You’ve already modifed the file controllers/home_controller.rb to include this:

def index
  @users = User.all
end

Now modify the file app/views/home/index.html.erb to look like this:

<h3>Home</h3>
<% @users.each do |user| %>
  <p>User: <%=link_to user.name, user %></p>
<% end %>

Create an Application Layout

Rails will use the layout defined in the file app/views/layouts/application.html.erb or app/views/layouts/application.html.haml as a default for rendering any page. Set up your application layout by modifying the default.

Set Up CSS Stylesheets

This step is the css_setup recipe from the fortuity/rails-template-recipes repository.

We’ll create a very simple stylesheet with styling for a horizontal menu and flash messages:

Create a public/stylesheets/application.css file:

ul.hmenu {
  list-style: none;	
  margin: 0 0 2em;
  padding: 0;
}
ul.hmenu li {
  display: inline;  
}
#flash_notice, #flash_alert {
  padding: 5px 8px;
  margin: 10px 0;
}
#flash_notice {
  background-color: #CFC;
  border: solid 1px #6C6;
}
#flash_alert {
  background-color: #FCC;
  border: solid 1px #C66;
}

The Default Application Layout

This step is the application_layout recipe from the fortuity/rails-template-recipes repository.

The default application layout app/views/layouts/application.html.erb looks like this:

<!DOCTYPE html>
<html>
<head>
  <title><%= app_name %></title>
  <%= stylesheet_link_tag :all %>
  <%= javascript_include_tag :defaults %>
  <%= csrf_meta_tag %>
</head>
<body>

<%= yield %>

</body>
</html>

If you are using Haml, remove app/views/layouts/application.html.erb and replace it with app/views/layouts/application.html.haml like this:

$ rm public/index.html

!!!
%html
  %head
    %title #{app_name}
    = stylesheet_link_tag :all
    = javascript_include_tag :defaults
    = csrf_meta_tag
  %body
    = yield

You’ll modify the default application layout in the next steps.

Include Flash Messages

Include flash messages in app/views/layouts/application.html.erb like this:

<body>
  <%- flash.each do |name, msg| -%>
    <%= content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String) %>
  <%- end -%>
<%= yield %>

For Haml, modify app/views/layouts/application.html.haml like this:

%body
  - flash.each do |name, msg|
    = content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String)
  = yield

Add Devise Navigation Links

This step is the devise_navigation recipe from the fortuity/rails-template-recipes repository.

You will want to add navigation links to the application layout for the Devise sign-up and log-in actions. You’ll find a simple example on the Devise wiki.

Create a menu directory under app/views/devise. Then create the file app/views/devise/menu/_login_items.html.erb and add:

<% if user_signed_in? %>
  <li>
  <%= link_to('Logout', destroy_user_session_path) %>        
  </li>
<% else %>
  <li>
  <%= link_to('Login', new_user_session_path)  %>  
  </li>
<% end %>

Create the file app/views/devise/menu/_registration_items.html.erb and add:

<% if user_signed_in? %>
  <li>
  <%= link_to('Edit account', edit_user_registration_path) %>
  </li>
<% else %>
  <li>
  <%= link_to('Sign up', new_user_registration_path)  %>
  </li>
<% end %>

Then use these partials in your app/views/layouts/application.html.erb file, like this:

<body>
  <ul class="hmenu">
    <%= render 'devise/menu/registration_items' %>
    <%= render 'devise/menu/login_items' %>
  </ul>
  <%- flash.each do |name, msg| -%>
    <%= content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String) %>
  <%- end -%>
<%= yield %>

For Haml, modify app/views/layouts/application.html.haml like this:

%body
  %ul.hmenu
    = render 'devise/menu/registration_items'
    = render 'devise/menu/login_items'
  - flash.each do |name, msg|
    = content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String)
  = yield

Cleanup

Remove Unneeded Files

This step is included in the cleanup recipe from the fortuity/rails-template-recipes repository.

Remove various unneeded files from your application:

$ rm public/favicon.ico
$ rm public/images/rails.png

In a previous step, you deleted the default home page from your application. But if you didn’t already:

$ rm public/index.html

Ban Spiders

This step is the ban_spiders recipe from the fortuity/rails-template-recipes repository.

You may want to modify the file public/robots.txt to prevent indexing by search engines if you plan to have a development version on a publicly accessible server:

# To ban all spiders from the entire site uncomment the next two lines:
User-Agent: *
Disallow: /

Test the App

You can check that your app runs properly by entering the command

$ rails server

To see your application in action, open a browser window and navigate to http://localhost:3000/. You should see the default user listed on the home page. When you click on the user’s name, you should be required to log in before seeing the user’s detail page.

Stop the server with Control-C.

Deploy to Heroku

Set Up Heroku

For your convenience, here are instructions for deploying your app to Heroku. Heroku provides low cost, easily configured Rails application hosting.

To deploy this app to Heroku, you must have a Heroku account. If you need to obtain one, visit http://heroku.com/ to set up an account.

Make sure the Heroku gem is in your Gemfile. If it’s not, add it and run

$ bundle install

to set up your gems again.

Add your public key immediately after installing the heroku gem so that you can use git to push or clone Heroku app repositories. See http://docs.heroku.com/heroku-command for details.

Create Your Application on Heroku

Use the Heroku create command to create and name your new app.

$ heroku create _myapp_

Heroku Add-on for MongoHQ

You can use a Heroku add-on to deploy your app using the MongoHQ service.

To enable the add-on, you can use the Heroku web interface or you can enter the following commands:

$ heroku addons:add mongohq:free

You can check that everything has been added correctly by running:

$ heroku info --app myapp

Set Up Your Application on Heroku

Push your application to Heroku:

$ git push heroku master

Initialize your application database:

$ heroku rake db:seed

If you get the error message “failed to connect to any given host:port”, you likely failed to set up your config/application.rb file to include the MongoHQ connection parameters.

Visit Your Site

Open your Heroku site in your default web browser:

$ heroku open

Troubleshooting

If you get errors, you can troubleshoot by reviewing the log files:

$ heroku logs

Conclusion

This concludes the tutorial for creating a Ruby on Rails web application that requires Rails 3 and uses Mongoid for data storage and Devise for user management and authentication.

Credits

Daniel Kehoe (http://danielkehoe.com/) implemented the application and wrote the tutorial.

Was this useful to you? Follow me on Twitter:
http://twitter.com/yaxdotcom
and tweet some praise. I’d love to know you were helped out by the tutorial.

Any issues? Please create an Issue on GitHub.

Contributors

Thank you to contributor Nakort Valles for updating to newer gems.

Thank you for improvements to the tutorial by contributors Cory Foy, Luca G. Soave, Bob Clewell, and Justin Workman.

Clone this wiki locally