我的第一个Ruby On Rails + MongoDB程序

最近想进一步学习一下MongoDB,而很久之前使用过ROR,正好也凑个机会重新拾起来。下面是建立第一个项目的过程。

主要参考文档:

1.Rails 3 - Getting started

2.MongoDB and MongoMapper(可能需要)

3.Getting started with VMware CloudFoundry, MongoDB and Rails(可能需要)

一、创建程序的框架

创建项目时不再使用rails active_record支持:

$ rails new todo -O

依次完成文档1中的所提示的步骤。

1. 编辑GemFile,增加下面的内容:

source "http://gemcutter.org" gem "mongo_mapper" 2. 执行

$ bundle install
安装项目的依赖包

3. 在config/initializer下面新建一个mongo.rb文件,指定全局的数据库信息:

MongoMapper.connection = Mongo::Connection.new('localhost', 27017) MongoMapper.database = 'todo' #为了简单起见,没有为不同的环境指定不同的数据 if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| MongoMapper.connection.connect if forked end end
4. 在lib目录下面新建一个mongo.rake文件(在本文中还没有用到)

namespace :db do namespace :test do task :prepare do # Stub out for MongoDB end end end
完成以上步骤后,启动程序:

$ rails server **Notice: C extension not loaded. This is required for optimum MongoDB Ruby driver performance. You can install the extension as follows: gem install bson_ext If you continue to receive this message after installing, make sure that the bson_ext gem is in your load path and that the bson_ext and mongo gems are of the same version. => Booting WEBrick => Rails 3.0.10 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2011-10-19 23:36:14] INFO WEBrick 1.3.1 [2011-10-19 23:36:14] INFO ruby 1.9.2 (2011-07-09) [x86_64-linux] [2011-10-19 23:36:14] INFO WEBrick::HTTPServer#start: pid=19595 port=3000

从上面输出中可以看到bson_ext库没有加载。首先按照提示安装该库:

sudo gem install bson_ext
然后编辑GemFile,加入下面一行:

gem "bson_ext"
再次启动程序,Notice提示消息消失,启动正常。在浏览器输入:http://127.0.0.1:3000,就可以看到如下页面:

我的第一个Ruby On Rails + MongoDB程序


二、添加页面和处理逻辑

通过rails的generate命令来生成页面、控制器和模型层文件:

$ rails generate scaffold project name:string --orm=mongo_mapper
命令执行完毕后,重新启动服务器,在浏览器输入中:http://127.0.0.1/projects,就可以看到如下:

我的第一个Ruby On Rails + MongoDB程序


点击New Project链接,添加一个新项目:

我的第一个Ruby On Rails + MongoDB程序

输入项目名称后,点击Create Project按钮保存

我的第一个Ruby On Rails + MongoDB程序

点击Back链接回到列表页面,可以看到新创建的项目blog,已经在列表里了:

我的第一个Ruby On Rails + MongoDB程序

登录到MongoDB数据库中可以查询到刚刚插入的数据:

我的第一个Ruby On Rails + MongoDB程序


到现在为止还没有写一行代码。不过先到这里吧,以后接着续。