In the past week i had tried mongodb in rails.
I rewrite my previous project money to use mongodb instead of active record.
The source code is in branch money-mongodb.
Here i record the steps of changing active record to mongodb
Install mongodb
I am using Mac OSX, very easy to install
1
brew install mongodb
Run mongodb in your shell
1
mongod
Update Gemfile
I choose mongoid gem because it has good documents and it’s a object document mapper framework.
I am familiar with SQL so i could catch up NonSQL database easily.
Need to add github: 'mongoid/mongoid' because Rails4.
Gemfile
1
gem'mongoid',github:'mongoid/mongoid'
Generate mongoid config
1
rails g mongoid:config
Mark active record related codes
In application.rb mark the require rails/all and add below.
Remember to unmark devise_for after new user.rb created.
New user.rb looks like below, it includes Mongoid::Document.
user.rb
12345678910111213
classUserincludeMongoid::Document# Include default devise modules. Others available are:# :confirmable, :lockable, :timeoutable and :omniauthabledevise:database_authenticatable,:registerable,:recoverable,:rememberable,:trackable,:validatable## Database authenticatablefield:email,:type=>String,:default=>""field:encrypted_password,:type=>String,:default=>""...end
Update models
Bascially we just need to include Mongoid::Document and add field
category.rb
1234567
# class Category < ActiveRecord::Base# endclassCategoryincludeMongoid::Documentfield:name,type:Stringfield:cid,type:Integerend
Update logic of querying data in model
This is the most difficult part. Model has methods to query data from database.
All need to rewrite.
# mark below # config.fixture_path = "#{::Rails.root}/spec/fixtures"# config.use_transactional_fixtures = true# unmark belowconfig.before(:suite)doDatabaseCleaner.strategy=:truncation# must be truncationendconfig.before(:each)doDatabaseCleaner.startendconfig.after(:each)doDatabaseCleaner.cleanend
In feature/env/rb
env.rb
12345
beginDatabaseCleaner.strategy=:truncation# must be truncationrescueNameErrorraise"You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."end
That’s it. But i still have a question not solved. During my trying the mongod process was crash easily and no idea why.
Error log like below.