Rails Tutorial for Devise with Mongoid

by Daniel Kehoe

Last updated 19 August 2012

Ruby on Rails tutorial showing how to create a Rails 3.2 application using Devise with Mongoid.

Devise gives you ready-made authentication and user management. Mongoid gives access to a MongoDB datastore for quick development without schemas or migrations. This tutorial also gives you the option of using jQuery, Haml, RSpec and Cucumber, showing how to integrate each option.

Similar Examples and Tutorials

Author Example App Comments
Plataformatec Devise Simple example using SQLite
Daniel Kehoe Devise, RSpec, Cucumber Detailed tutorial, app template, starter app, using SQLite
Daniel Kehoe OmniAuth, Mongoid Detailed tutorial, app template, starter app, using MongoDB

See a list of additional Rails examples, tutorials, and starter apps.

Follow on Twitter Follow on Twitter

Follow the project on Twitter: rails_apps. Tweet some praise if you like what you’ve found.

Tutorial 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. See recommendations for a Rails tutorial and resources for getting started with Rails.

Before You Start

If you follow this tutorial closely, you’ll have a working application that closely matches the example app in this GitHub repository. The example app is your reference implementation. If you find problems with the app you build from this tutorial, download the example app (in Git speak, clone it) and use a file compare tool to identify differences that may be causing errors. On a Mac, good file compare tools are FileMerge, DiffMerge, Kaleidoscope, or Ian Baird’s Changes.

If you clone and install the example app and find problems or wish to suggest improvements, please create a GitHub issue.

To improve this tutorial, please leave comments below.

Installing MongoDB

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 mongodb

Homebrew will provide post-installation instructions to get MongoDB running. The last line of the installation output shows you the MongoDB install location (for example, /usr/local/Cellar/mongodb/1.8.0-x86_64). You’ll find the MongoDB configuration file there. After an installation using Homebrew, the default data directory will be /usr/local/var/mongodb.

On the Debian GNU/Linux operating system, as of March 2013, the latest stable version is MongoDB 2.0.0. With MongoDB 2.0.0, the Mongoid gem must be version 3.0.×. See the Mongoid installation instructions. Change your Gemfile to use an earlier Mongoid version:

gem 'mongoid', '~> 3.0.1'

Creating the Application

You have several options for getting the code. You can copy from the tutorial, fork, clone, or generate.

Copy from the Tutorial

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.

Fork

If you’d like to add features (or bug fixes) to improve the example application, you can fork the GitHub repo and make pull requests. Your code contributions are welcome!

Clone

If you want to copy and customize the app with changes that are only useful for your own project, you can download or clone the GitHub repo. You’ll need to search-and-replace the project name throughout the application. You probably should generate the app instead (see below).

Generate

You can use the Rails Composer tool to generate a new version of the example app. You’ll be able to give it your own project name when you generate the app. Generating the application gives you additional options.

To build the example application, run the command:

$ rails new rails3-mongoid-devise -m https://raw.github.com/RailsApps/rails-composer/master/composer-Rails3_2.rb -T -O

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

The $ character indicates a shell prompt; don’t include it when you run the command.

This creates a new Rails app named rails3-mongoid-devise on your computer. You can use a different name if you wish.

You’ll see a prompt:

question  Install an example application?
      1)  I want to build my own application
      2)  rails3-bootstrap-devise-cancan
      3)  rails3-devise-rspec-cucumber
      4)  rails3-mongoid-devise
      5)  rails3-mongoid-omniauth
      6)  rails3-subdomains

Choose 4) rails3-mongoid-devise.

The application generator template will ask you for additional preferences.

For this tutorial, choose “WEBrick” for your development webserver.

You can choose to set a robots.txt file to ban spiders and keep your site out of Google search results.

If you are a Linux user and you haven’t installed node.js, you’ll need to answer “yes” to install the ‘therubyracer’ JavaScript runtime.

If you have installed rvm, the Ruby Version Manager, I recommend you answer “yes” to the prompt, “Use or create a project-specific rvm gemset?” See the article Installing Rails to learn about the benefits of using rvm.

Finally, the program will ask if you want to create a GitHub repository.

If you get an error “You have already activated (…) but your Gemfile requires (…)”, try deleting the rails3-mongoid-devise folder and running the command again.

Assumptions

Before beginning this tutorial, you need to install

  • The Ruby language (version 1.9.3 or newer)
  • Rails 3.2

Check that appropriate versions of Ruby and Rails are installed in your development environment:

$ ruby -v
$ rails -v

Be sure to read Installing Rails for detailed instructions and advice.

Create the Rails Application

Beginning here, we show how to create the application from scratch.

(This has already been done for you if you use the the Rails Composer tool.)

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

$ rails new rails3-mongoid-devise -T -O

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

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

If you’re open sourcing the app on GitHub, please edit the README file to add a description of the app and your contact info. Changing the README is important if you’re using a clone of the example app. I’ve been mistaken (and contacted) as the author of apps that are copied from my example.

Set Up Source Control (Git)

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.

$ git init .
$ git add .
$ git commit -m 'Initial commit'

See detailed instructions for Git and Rails.

Set Up Gems

About Required Gems

The application uses the following gems:

Set up Your Gemfile

It’s a good idea to create a new gemset using rvm, the Ruby Version Manager, as described in the article Installing Rails.

See Example Gemfiles for Rails 3.2.

Open your Gemfile and replace the contents with the following:

Gemfile

source 'https://rubygems.org'
gem 'rails', '3.2.13'
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem "mongoid", ">= 3.0.3"
gem "rspec-rails", ">= 2.11.0", :group => [:development, :test]
gem "capybara", ">= 1.1.2", :group => :test
gem "database_cleaner", ">= 0.8.0", :group => :test
gem "mongoid-rspec", ">= 1.4.6", :group => :test
gem "email_spec", ">= 1.2.1", :group => :test
gem "cucumber-rails", ">= 1.3.0", :group => :test, :require => false
gem "launchy", ">= 2.1.2", :group => :test
gem "factory_girl_rails", ">= 4.0.0", :group => [:development, :test]
gem "devise", ">= 2.1.2"

Check for the current version of Rails and replace gem 'rails', '3.2.13' accordingly.

Note: The RailsApps examples are generated with application templates created by the Rails Apps Composer Gem. For that reason, groups such as :development or :test are specified inline. You can reformat the Gemfiles to organize groups in an eye-pleasing block style. The functionality is the same.

Install the Required Gems

When you add a new gem to the Gemfile, you should run the bundle install command to install the required gems on your computer. Run:

bundle install

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

$ gem list

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.

Haml

In this tutorial, we’ll use the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml. See instructions for Haml and Rails.

Adding RSpec for Unit Testing

If you are creating an application template, this step uses the rspec recipe from the rails_apps_composer repository.

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.

Install RSpec and Related Gems

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

Add the following to your Gemfile file:

gem 'rspec-rails', :group => [:development, :test]
gem 'database_cleaner', :group => :test
gem 'factory_girl_rails', :group => :test
gem 'mongoid-rspec', :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.

The gems mongoid-rspec and factory_girl_rails add additional capabilities (described below).

Install the required gems on your computer:

$ bundle install

Generate RSpec

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

$ rails generate rspec:install

You can remove the test folder (it is not needed for RSpec):

$ rm -rf test/

You can also modify the config/application.rb file to remove the following:

require 'rails/test_unit/railtie'

Suppress Spec Tests for Views and Helpers

When RSpec is installed, Rails generators create specs for views and helpers when the rails generate controller or rails generate scaffold commands are run. If you don’t want specs for views and helpers, modify the config/application.rb file to add the following:

class Application < Rails::Application

  config.generators do |g|
    g.view_specs false
    g.helper_specs false
  end

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

Add RSpec Matchers for Mongoid

Matchers provide ready-made code for your specs, allowing you to quickly add tests for common features. If you are writing specs for ORM features such as validation in Rails models, you will need matchers customized for RSpec and Mongoid. Two similar gems are available: mongoid-rspec and remarkable_mongoid. We use mongoid-rspec in this example. You’ll need gem 'mongoid-rspec', :group => :test in your Gemfile.

Create a file spec/support/mongoid.rb:

RSpec.configure do |config|
  config.include Mongoid::Matchers
end

Now you can use the RSpec matchers for Mongoid when you write tests. Keep in mind that it may be worthwhile to test validations using ORM matchers but testing of associations is often redundant because Mongoid is well-tested. In general, it is preferable to use Cucumber scenarios to test higher-level functionality and reduce dependency on a specific ORM (see a discussion).

Add Factory Girl for Test Objects

The Factory Girl gem is used to create default model objects for tests. For example, if a controller action requires finding a User object before displaying a “show” page, Factory Girl will create a user just for a test of the controller. You’ll need gem 'factory_girl_rails', :group => :test in your Gemfile.

You’ll need a spec/factories.rb file to contain the factory definitions for any default objects used for testing. The example spec directory contains an implementation.

Add Devise Test Helpers

Using Devise, your controllers will often include before_filter :authenticate_user! to limit access to signed-in users. Your tests will fail unless a default user is created and logs in before each test runs. Devise provides test helpers to make it simple to create and log in a default user.

Create a file spec/support/devise.rb:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

Now you can write controller specs that set up a signed-in user before tests are run.

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. If you run rake spec after adding our ready-made specs, you’ll see an error such as Uninitialized constant ... (NameError) because you haven’t created models or controllers. You’ll have to complete the tutorial before rake spec will run successfully.

Add Cucumber for Behavior Driven Development

If you are creating an application template, this step uses the cucumber recipe from the rails_apps_composer repository.

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.

This tutorial shows how to set up Cucumber with Devise.

Cucumber Gems

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

You should have the following gems in your Gemfile file:

group :test do
  gem 'cucumber-rails'
  gem 'capybara'
  gem 'database_cleaner'
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.

Modify the file features/support/env.rb like this:

begin
  DatabaseCleaner.orm = 'mongoid'
  DatabaseCleaner.strategy = :truncation
rescue NameError
  raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end

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”.

Write Cucumber Scenarios

To learn more about using Cucumber, refer to The Cucumber Book or the free introduction to Cucumber, The Secret Ninja Cucumber Scrolls.

There are two approaches to writing Cucumber scenarios. The newest (and recommended) approach uses Capybara to write the code (“steps”) that turn Cucumber scenarios into executable specifications. Older versions of Cucumber provided a web_steps.rb file that implemented common features. See the The Training Wheels Came Off by Aslak Hellesøy to understand why the web_steps.rb approach is no longer recommended.

Use Mongoid

If you are creating an application template, this step uses the mongoid recipe from the rails_apps_composer 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

If you are creating an application template, this step uses the action_mailer recipe from the rails_apps_composer 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 commenting out the line in the file:

# 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

If you are creating an application template, this step uses the devise recipe from the rails_apps_composer repository.

This app uses Devise for user management and authentication. Devise is at https://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.

Accommodate Cucumber Testing for “Sign Out”

By default, Devise uses an http DELETE request for sign out requests (destroy_user_session_path). Rails uses Javascript to implement http DELETE requests. Prior to Devise 1.4.1 (27 June 2011), Devise used an http GET request for sign out requests. Jose Valim explained the change: “GET requests should not change the state of the server. When sign out is a GET request, CSRF can be used to sign you out automatically and things that preload links can eventually sign you out by mistake as well.”

However, Cucumber wants to test GET requests not DELETE requests. If you intend to use Cucumber with Devise, you must change the Devise default from DELETE to GET in config/initializers/devise.rb for the Rails test environment. You may see a suggestion elsewhere to tweak the routes.rb file or change the log_out link to make the fix. It isn’t necessary if you change the config/initializers/devise.rb file.

# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = Rails.env.test? ? :get : :delete

Since you only use Cucumber during testing, switching the default is only needed for testing.

If you’re not going to use Cucumber, leave Devise’s new default (DELETE) in place.

Prevent Logging of Passwords

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

app/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

If you are creating an application template, this step uses the add_user recipe from the rails_apps_composer 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 (ERB)

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.

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 Customized Views for User Registration (Haml)

If you are using Haml, Devise does not generate views for Haml (it did before February 15, 2011; see Devise issue 878).

You can create the files:

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

%h2
  Edit #{resource_name.to_s.humanize}
= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f|
  = devise_error_messages!
  %p
    = f.label :name
    %br/
    = f.text_field :name
  %p
    = f.label :email
    %br/
    = f.email_field :email
  %p
    = f.label :password
    %i (leave blank if you don't want to change it)
    %br/
    = f.password_field :password
  %p
    = f.label :password_confirmation
    %br/
    = f.password_field :password_confirmation
  %p
    = f.label :current_password
    %i (we need your current password to confirm your changes)
    %br/
    = f.password_field :current_password
  %p= f.submit "Update"
%h3 Cancel my account
%p
  Unhappy? #{link_to "Cancel my account", registration_path(resource_name), :confirm => "Are you sure?", :method => :delete}.
= link_to "Back", :back

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

%h2 Sign up
= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
  = devise_error_messages!
  %p
    = f.label :name
    %br/
    = f.text_field :name
  %p
    = f.label :email
    %br/
    = f.email_field :email
  %p
    = f.label :password
    %br/
    = f.password_field :password
  %p
    = f.label :password_confirmation
    %br/
    = f.password_field :password_confirmation
  %p= f.submit "Sign up"
= render :partial => "devise/shared/links"

Create a Home Page

If you are creating an application template, this step uses the home_page recipe from the rails_apps_composer 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

If you are creating an application template, this step uses the home_page_users recipe from the rails_apps_composer repository.

Modify the file app/controllers/home_controller.rb and add users = User.all to the index method:

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

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

puts 'SETTING UP DEFAULT USER LOGIN'
user = User.create! :name => 'First User', :email => 'user@example.com', :password => 'please', :password_confirmation => 'please'
puts 'New user created: ' << user.name
user2 = User.create! :name => 'Second User', :email => 'user2@example.com', :password => 'please', :password_confirmation => 'please'
puts 'New user created: ' << user2.name

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

Seed the Database

Create indexes for the database with:

$ rake db:mongoid:create_indexes

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

$ rake db:seed

If the task fails with “Validation failed: Name can’t be blank” you should check that the file models/user.rb allows the “name” attribute to be mass updated:

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

During testing, if you wish to reset the MongoDB database you can run the command:

$ rake db:drop

Be sure to recreate the idnexes after dropping the database.

If you’re not using rvm, you should preface each rake command with bundle exec. You don’t need to use bundle exec if you are using rvm version 1.11.0 or newer.

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

If you are creating an application template, this step uses the users_page recipe from the rails_apps_composer 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 app/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

Important note: The devise_for :users route must be placed above resources :users.

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 app/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

Set Up CSS Stylesheets

If you are creating an application template, this step uses the html5 recipe from the rails_apps_composer repository

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

Rename the app/assets/stylesheets/application.css file as app/assets/stylesheets/application.css.scss.

Add stylesheet rules to the application.css.scss file:

header nav ul {
  list-style: none;
  margin: 0 0 2em;
  padding: 0;
}
header nav ul 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

If you are creating an application template, this step uses the application_layout recipe from the rails_apps_composer repository.

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.

You’ll want to include flash messages for errors and notifications. Set up your application layout by modifying the default as described in the instructions for the Rails default application layout.

Add Devise Navigation Links

If you are creating an application template, this step uses the navigation recipe from the rails_apps_composer 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 shared directory under app/views/. Then create the file app/views/shared/_navigation.html.erb and add:

<% if user_signed_in? %>
  <li>
  <%= link_to('Logout', destroy_user_session_path, :method=>'delete') %>
  </li>
<% else %>
  <li>
  <%= link_to('Login', new_user_session_path)  %>
  </li>
<% end %>
<% 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 'shared/navigation' %>
  </ul>
  <% flash.each do |name, msg| %>
    <% if msg.is_a?(String) %>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    <% end %>
  <% end %>
<%= yield %>

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

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

Cleanup

Several unneeded files are generated in the process of creating a new Rails application.

Additionally, you may want to prevent search engines from indexing your website if you’ve deployed it publicly while still in development.

See instructions for cleaning up unneeded files in Rails and banning spiders.

Remove Unneeded Files

If you are creating an application template, this step uses the cleanup recipe from the rails_apps_composer repository.

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

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

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:
rails_apps
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 for improvements to the tutorial by contributors Cory Foy, Luca G. Soave, Bob Clewell, and Justin Workman.

Comments

Is this helpful? Your encouragement fuels the project. Please tweet or add a comment. Couldn't get something to work? For the example apps and tutorials, it's best to open an issue on GitHub so we can help you.

comments powered by Disqus