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

8 篇文章 0 订阅
7 篇文章 0 订阅

    最近想进一步学习一下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,就可以看到如下页面:



二、添加页面和处理逻辑

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

$ rails generate scaffold project name:string --orm=mongo_mapper

命令执行完毕后,重新启动服务器,在浏览器输入中:http://127.0.0.1/projects,就可以看到如下:



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


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

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


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



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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mydeman

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值