Tweetegy On the edge of chaos with Ruby, Rails, JavaScript and AngularJS.

| About | Search | Archive | Github | RSS |

Using MongoDB as a logging database with a Rails 3 application

Here is a great article on the MongoDB site that explains how to setup Rails 3 to work with MongoDB with very little effort!

Essentially this means doing the following things.

Create a new Rails 3 application issuing the skip-active-record switch

rails new my_app --skip-active-record

Add the following line to include mongo_mapper to your gemfile

gem "mongo_mapper"

Now run the bundle installer

bundle install

Finally, add this initializer to your Rails 3 project to connect to your MongoDB app:

1 MongoMapper.connection ='localhost', 27017)
2 MongoMapper.database = "#myapp-#{Rails.env}"
4 if defined?(PhusionPassenger)
5  PhusionPassenger.on_event(:starting_worker_process) do |forked|
6    MongoMapper.connection.connect_to_master if forked
7  end
8 end

Now it's time to create our dummy action:

rails g controller DummyAction simulate

Creating models that use MongoMapper is very easy. This is a good thing because, at the time of wrting, Rails 3 generators for MongoMapper are not included, so you might end up trying what I did and getting “No value provided for required options ‘–orm’” error and then trying all combinations under the sun for the orm switch to get the generator to work! If you want to use generators then try Rails 3 generators, which is a project that simply has: “Rails 3 compatible generators for gems that don’t have them yet”

So I created my own models by hand because it is so easy to do. A typical MongoMapper model might look like this WebAppVisitorLog class of mine:

1 class WebAppVisitorLog
2   include MongoMapper::Document
4   key :session_id, Integer
5   key :user_id, Integer
6 end

Finally, what to do with the action? Well push a log entry to MongoDB like so:

 1 class DummyActionController < ApplicationController
 2   def simulate
 3     #log some fake data in Mongo DB
 4     @log = WebAppVisitorLog.create(
 5     {
 6       :session_id => 1,
 7       :user_id => 1,
 8       :updated_at =>
 9     })
11   end
12 end

Be sure to add this to your config.rb file also:

1 get "dummy_action/simulate"