前邊有介紹mongodb的安裝以及ror項目的搭建,現在進行一下整合。
1.創建項目
創建項目時不再使用rails active_record支持
rails new todo -O
2.我們將要使用MongoMapper來驅動MongoDB到Rails
編輯GemFile,增加下面的內容
gem"mongo_mapper"
然后 執行 bundle install 安裝gem
bundle install
3.添加數據庫鏈接
在config/initializer下面新建一個mongo.rb文件,指定全局的數據庫信息:
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)MongoMapper.database ='todo'#通過指定Rails運行環境參數,我們可以在不同的運行環境下創建互不干擾的數據,為了簡單起見,沒有為不同的環境指定不同的數據
if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process)do|forked| MongoMapper.connection.connectifforked endend
完成以上步驟后,啟動程序:
$ 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 thebson_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庫沒有加載。按照提示安裝該庫即可(別忘了在gemfile中添加gem):
再次啟動程序,Notice提示消息消失,啟動正常。在瀏覽器輸入:http://127.0.0.1:3000,就可以看到如下頁面
4.添加頁面和處理邏輯
通過rails的generate命令來生成頁面、控制器和模型層文件(個人還是喜歡自己手動創建,這里為了演示方便)
rails generate scaffold project name:string --orm=mongo_mapper
由于我們使用mongo作為數據庫。那么,我們需要把ActiveRecord的model,改成MongoMapper的類型,也就是把繼承關系從ActiveRecord::Base變成MongoMapper::Document。我們使用key這個方法標明該MongoMapper的字段屬性。我們的屬性是name,再加上這個字段的類型String,那么定義如下:
classProject include MongoMapper::Document key:name,Stringend
通過以上的修改,我們就已經擁有了所有添加,更新,刪除和列表的操作
新聞熱點
疑難解答