Rails3 and MongoDB Quick Guide_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Rails3 and MongoDB Quick Guide

Rails3 and MongoDB Quick Guide

 2010/12/11 11:30:14  hideto  http://hideto.javaeye.com  我要评论(0)
  • 摘要:InstallMongoDBDownload:http://www.mongodb.org/downloadsExtractthefilestoadirectory(e.g,/opt/mongodb)Createdatadirectory:$sudomkdir-p/data/dbStartMongoDBserver:$sudo/opt/mongodb/bin/mongodStartshellandconnectiontoMongoDBserverfortest
  • 标签:rails rails3 ide MongoDB
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')>]
发表评论
用户名: 匿名