Rails3 and MongoDB Quick Guide

[b]Install MongoDB[/b]
Download:
[url]http://www.mongodb.org/downloads[/url]
Extract the files to a directory(e.g, /opt/mongodb)

Create data directory:
[code]
$ sudo mkdir -p /data/db
[/code]

Start MongoDB server:
[code]
$ sudo /opt/mongodb/bin/mongod
[/code]

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

[b]Install Rails3 and mongo_mapper[/b]
[code]
sudo gem install rails
sudo gem install mongo_mapper
sudo gem install bson_ext
[/code]

[b]Create Rails project that use MongoDB[/b]
Create project:
[code]
$ rails new MongoDBTest --skip-active-record
[/code]

Edit the Gemfile:
[code]
gem 'rails', '3.0.3'
gem 'mongo_mapper'
gem 'bson_ext'
[/code]

Create config/initializers/mongo.rb:
[code]
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
[/code]

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

key :name
end
[/code]

Start Rails Console for test:
[code]
$ 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')>]
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值