ActiveMongo

ActiveMongo is a Rails 3.0 and Ruby 1.9 compatible Mongo ORM.

It currently supports all common validations, find (single or many items) and has_many association.

Feel free to it if you’re adventurous.

Installation

  1. Add to your Rails application Gemfile
  2. Run gem bundle
  3. Load gem. For example, create initializer that says “require ‘active_mongo’”
  4. Create config/mongo.yml. Format is the same as database.yml. Database, host and port are required. User and password are optional
  5. Create a model, which is a subclass of ActiveMongo::Base

Usage

Validations

All ActiveModel validations are supported. validates_uniqueness_of with optional :scope => [:column] is available too.

Collection methods


  Model.find(ID) # get by ID
  Model.find #get whole collection
  Model.find(args) #run a query, args are the same as for mongo_ruby_driver 
  
  Model.destroy_all
  Model.destroy_all(args)

Create an object


  Model.new()
  Model.new(:attribute => "value")
  
  Model.save

Update an object


  object.attribute = "value" #No need to declare anywhere before setting, see?
  object.update_attributes(:attribute => "value") #does not save!
  
  object.unset(:attribute) #removes :attribute from the object and saves ONLY this change
  
  object.save
  object.save(false) #do not run validations

Destroy object


  object.destroy

HasMany Associations


  #in model
  has_many :items#, :class_name => "Item", :foreign_key => "item_id"
  
  #in code
  object.items.find()
  object.items.remove_all()
  object.items.new()

Mass assignment

You can limit what may be assigned by passing a hash to #new or #update_attributes with this option.


  attr_accessible :attribute

Do not save specific field to database


  attr_clear :attribute

Indexes


  ensure_index :attribute
  ensure_index :attribute, :unique => true
  ensure_index [ [:attribute, Mongo::ASCENDING] ], :unique => true # takes mongo-driver syntax

Callbacks

after initialize and before/after/around create, update and save callbacks are supported


  after_save :method

Named Scopes


  #in model
  named_scope :with_value, :attribute => :value #all mongo_driver find() parameters accepted
  
  #in code
  Model.with_value #returns scoped class
  Model.with_value.find() #run find with scope
  Model.with_value.new() #initialize an object with scope

Coming soon

  • Documentation
  • Tests
  • Even more goodies

License

This code is distributed under MIT license.