Tags

, ,


I recently used MongoDB at my work for mobile app and was tempted to try more. So i wrote a simple app in rails to play with it..

Lets assume rails is already installed.

References for tutorial:
MongoDb installation
MongoDB with Rails
Railcast of integrating rails with Mongo

The installation of MongoDB can be done using the first reference.
Lets create a rails project now to record daily expenses.

rails new expense_record --skip-active-record

We need to update the gemfile by adding mongo dependencies:

require 'rubygems'
require 'mongo'

gem 'rails', '3.0.10'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
source 'http://gemcutter.org'

gem "mongo_mapper"
gem "bson_ext", "1.3.1"
gem "bson" ,"1.3.1"
gem  "mongo","1.3.1"

Now run

bundle install

Create a new filemongo_config.rb in config/initializers folder.
Lets add the following code :

MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "#expense-#{Rails.env}"

if defined?(PhusionPassenger)
   PhusionPassenger.on_event(:starting_worker_process) do |forked|
     MongoMapper.connection.connect if forked
   end
end

NOTE: here the #expense is the name of the database. By default Mongo listens to 27017 port. Also the database name should not contain “.”, such as “expense1.0″ is wrong.

Now lets create an expense model with field “expense_name” “date_spent” “amount”.

rails g scaffold expense expense_name:string date_spent:string amount:integer --skip-migration --orm mongo_mapper

All the classes are created as expected except the model class expense

class Expense
  include MongoMapper::Document

  key :expense_name, String
  key :date_spent, String
  key :amount, Integer

end

Instead of ActiveRecord , MongoMapper is used which behaves pretty much the same.

Now we are good to run the project.

rails s 
<a href="http://localhost:3000/expenses"></a>

Happy coding..

About these ads