Rails3 and MongoDB Quick Guide

阅读更多
Install MongoDB
Download:
http://www.mongodb.org/downloads
Extract the files to a directory(e.g, /opt/mongodb)

Create data directory:
$ sudo mkdir -p /data/db


Start MongoDB server:
$ sudo /opt/mongodb/bin/mongod


Start shell and connection to MongoDB server for test:
$ /opt/mongodb/bin/mongo
> db.foo.save( { a : 1} )
> db.foo.find()
> exit


Install Rails3 and mongo_mapper
sudo gem install rails
sudo gem install mongo_mapper
sudo gem install bson_ext


Create Rails project that use MongoDB
Create project:
$ rails new MongoDBTest --skip-active-record


Edit the Gemfile:
gem 'rails', '3.0.3'
gem 'mongo_mapper'
gem 'bson_ext'


Create config/initializers/mongo.rb:
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "MongoDBTest-production"

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


Create a model app/models/user.rb:
class User
  include MongoMapper:Document

  key :name
end


Start Rails Console for test:
$ rails console production
>> User.create(:name => "User A")
=> #
>> User.create(:name => "User B")
=> #
>> User.all
=> [#, #]

你可能感兴趣的:(MongoDB,Rails,EXT)