Recently, I had a task which used MongoDB as its database. At the beginning, I used MongoMapper as the ORM but finally I found out that I couldn’t use Devise with MongoMapper as the ORM. After searched some articles, it said that I need to use Mongoid if I were to use Devise as its application’s authorization mechanism. Right now, I want to share you my experience installing those two stuffs in Rails 3.
These are the steps to install mongoid in your rails 3 :
- Run command
gem install mongoid --pre
- Run command
gem install bson_ext
- Put those installed gems in your Gemfile
gem "mongoid", "2.0.0.rc.7"
gem "bson_ext", "1.2.4"
- To make sure that everything’s installed properly, please run :
- Now you can run command
rails generate mongoid:configand it will generate a file config/mongoid.yml
- Open up file config/application.rb and throw away require ‘rails/all’ and add these code as the replacement
That’s it and your mongoid has been set up well.
If you find it hard to understand how to configure devise here, you can refer to its origin page in https://github.com/plataformatec/devise. I’ll try to guide you step by step according to my experience with it.
- Install devise gem by running
gem install devise
- After installed successfully, you need to install it in your app by running
rails generate devise:install. You’ll see it generates a devise configuration file. To make sure everything will be okay, open it, and see whether it already contains
- To get a model, simply by running command
rails generate devise MODEL. This MODEL you can change with any name you want, in my case I replace it with Admin
- Well, actually devise is configured already. Now, you just need to configure a little thing in model file (app/models/admin.rb).
- Don’t forget to check you config/routes.rb file. Check whether it contains code
devise_for :adminsyet or not.
- To test it, try generate a controller rails generate controller admins. Open file app/controller/admins_controller.rb and put
before_filer :authenticate_admin!(admin can be changed depend on MODEL name you used)
Well, your devise is already set up for mongoid. You can run your application well, but don’t forget to start your mongodb server first.