Ruby on Rails - Devise and Mongoid
Ruby on Rails applications commonly use the Clearance and Devise authentication gems. The Clearance gem requires ActiveModel and therefore cannot work with MongoDB. However, the Devise gem has the ability to use Mongoid instead of ActiveRecord.
To begin, we create a new Rails project:
rails new authdemo --skip-active-record --skip-test --skip-system-test
We then install mongoid:
echo "gem 'mongoid'" >> Gemfile
bundle install
rails g mongoid:config
We then install the Devise gem:
echo "gem 'devise'" >> Gemfile
bundle install
rails g devise:install
rails g devise User
We then create a user that we will use to log into the application using the Rails console:
rails c
user = User.create! :email => 'user@example.com', :password => '123456', :password_confirmation => '123456'
Then, we create a controller…
rails g scaffold Something name:string
and enforce authentication for actions within that controller (after the class SomethignController
… line): before_action :authenticate_user!
On executing the application with rails s
and attempting to access any of the routes associated with the Something controller, we observe that we are redirected to the login page and are able to login with the new credentials defined in the MongoDB database.