Tweetegy On the edge of chaos with Blockchain, Dapps, DeFi, JavaScript

| 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
2
3
4
5
6
7
8
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "#myapp-#{Rails.env}"

if defined?(PhusionPassenger)
 PhusionPassenger.on_event(:starting_worker_process) do |forked|
   MongoMapper.connection.connect_to_master if forked
 end
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
2
3
4
5
6
class WebAppVisitorLog
  include MongoMapper::Document

  key :session_id, Integer
  key :user_id, Integer
end

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

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

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

1
get "dummy_action/simulate"