欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Rails3 and MongoDB Quick Guide 博客分类: Ruby MongoDBRailsEXT 

程序员文章站 2024-02-22 16:45:28
...
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 name: "User A", _id: BSON::ObjectId('4d01c70d98d1b1072b000001')>
>> User.create(:name => "User B")
=> #<User name: "User B", _id: BSON::ObjectId('4d01c70f98d1b1072b000002')>
>> User.all
=> [#<User name: "User A", _id: BSON::ObjectId('4d01c70d98d1b1072b000001')>, #<User name: "User B", _id: BSON::ObjectId('4d01c70f98d1b1072b000002')>]
相关标签: MongoDB Rails EXT