佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Ruby on Rails框架程序連接MongoDB的教程

Ruby on Rails框架程序連接MongoDB的教程

熱門標簽:Win7旗艦版 百度AI接口 電話運營中心 硅谷的囚徒呼叫中心 企業(yè)做大做強 呼叫中心市場需求 語音系統(tǒng) 客戶服務

前邊有介紹mongodb的安裝以及ror項目的搭建,現(xiàn)在進行一下整合。

1.創(chuàng)建項目

創(chuàng)建項目時不再使用rails active_record支持

rails new todo -O

2.我們將要使用MongoMapper來驅(qū)動MongoDB到Rails

編輯GemFile,增加下面的內(nèi)容

gem"mongo_mapper"

然后  執(zhí)行 bundle install 安裝gem

bundle install

3.添加數(shù)據(jù)庫鏈接

在config/initializer下面新建一個mongo.rb文件,指定全局的數(shù)據(jù)庫信息:

MongoMapper.connection = Mongo::Connection.new('localhost', 27017)


MongoMapper.database ='todo'#通過指定Rails運行環(huán)境參數(shù),我們可以在不同的運行環(huán)境下創(chuàng)建互不干擾的數(shù)據(jù),為了簡單起見,沒有為不同的環(huán)境指定不同的數(shù)據(jù)

if defined?(PhusionPassenger)

  PhusionPassenger.on_event(:starting_worker_process)do|forked|

    MongoMapper.connection.connectifforked

  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庫沒有加載。按照提示安裝該庫即可(別忘了在gemfile中添加gem):

再次啟動程序,Notice提示消息消失,啟動正常。在瀏覽器輸入:http://127.0.0.1:3000,就可以看到如下頁面

4.添加頁面和處理邏輯

通過rails的generate命令來生成頁面、控制器和模型層文件(個人還是喜歡自己手動創(chuàng)建,這里為了演示方便)

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

由于我們使用mongo作為數(shù)據(jù)庫。那么,我們需要把ActiveRecord的model,改成MongoMapper的類型,也就是把繼承關(guān)系從ActiveRecord::Base變成MongoMapper::Document。我們使用key這個方法標明該MongoMapper的字段屬性。我們的屬性是name,再加上這個字段的類型String,那么定義如下:

classProject

  include MongoMapper::Document

  key:name,String

end

通過以上的修改,我們就已經(jīng)擁有了所有添加,更新,刪除和列表的操作

5.數(shù)據(jù)查看

可以通過命令mongo進入mongodb數(shù)據(jù)庫進行數(shù)據(jù)的查詢

mongo //進入數(shù)據(jù)庫

use todo //切換庫

db.projects.find() //執(zhí)行查詢


6.其他

MongoMapper和ActiveRecord是完全相同的。甚至,MongoMapper還是支持ActiveRecord的驗證方式如下

validates_presence_of:name

由于MongoDB沒有schema-less(數(shù)據(jù)版本記錄)我們可以非常容易的添加和更改model的屬性,而不需要執(zhí)行任何migrations的操作。比如,我們需要添加一個priority的屬性,我們僅僅需要的是修改Project model如下:

classProject

  include MongoMapper::Document

  key:name,String,:required=>true

  key:priority,Integer

end

表之間的關(guān)聯(lián)對于MongoDB這里稍微有點區(qū)別,我們需要ObjectId類型來存儲所有id。

至于,處理不同表之前的關(guān)聯(lián),我們可以像ActiveRecord一樣定義belongs_to,當然,稍微有點不同,在Project中我們需要定義has_many :tasks,在MongoMapper中需要用many代替。

我目前也就做到這里。有時間再去深入研究其他的功能。

PS:Ruby編寫MongoDB備份腳本(fsync lock)

#!/usr/local/bin/ruby
# date:    06-12-2014
# auther: lucifer
# use fsync and lock to the file-system before backup the file-system
# mongo-ruby-driver version > 1.10.0

require 'mongo'
require 'fileutils'
require 'date'

include Mongo
include BSON

# the members of replcation-set
# test mongodb server version 2.6.0
# host = "192.168.11.51"

# The port of members
# If the port is 27017 by default then otherport don't need to assignment
# otherport = ""
# port = otherport.length != 0 ? otherport : MongoClient::DEFAULT_PORT

# opts = {:pool_size => 5, :pool_timeout => 10}
# Create a new connection
# client = MongoClient.new(host, port, opts)

uri_string = "mongodb://caoqing:xxxxxxxx@x.x.x.x:27017/admin"
client = MongoClient.from_uri(uri = "#{uri_string}")
db = client['admin']

# fsync and lock the database
cmd = OrderedHash.new
cmd[:fsync] = 1
cmd[:lock] = true
# p cmd
db.command(cmd)

# datafile path
d = "/var/lib/mongo"

# dir = Dir.new("#ye0gkmc")
# entries = dir.entries
# entries.delete_if { |entry| entry =~ /^\./}
# convert the relative path to the full path
# entries.map! { |entry| File.join(dir.path, entry) }
# maintain only the type of file
# entries.delete_if { |entry| !File.file?(entry) }
# p entries

start = Date.today.to_s
prev = (Date.today - 7).to_s

dest = "/backup/#{start}"
sour = "/backup/#{prev}"

FileUtils.rm_rf("#{sour}") if File::exist?("#{sour}")

Dir.mkdir("#{dest}", 0755) unless File::exist?("#{dest}")

FileUtils.cp_r Dir.glob("#msk0m0s/**"), dest if client.locked?

puts "*" * 20
puts "\tbackup complete"
puts "*" * 20

# DB::SYSTEM_COMMAND_COLLECTION
# unlock the database
db["$cmd.sys.unlock"].find_one
client.close

您可能感興趣的文章:
  • 淺談Ruby on Rails下的rake與數(shù)據(jù)庫數(shù)據(jù)遷移操作
  • Ruby連接使用windows下sql server數(shù)據(jù)庫代碼實例
  • 在Ruby程序中連接數(shù)據(jù)庫的詳細教程
  • Ruby中訪問SQL Server數(shù)據(jù)庫的配置實例
  • ruby+nokogori抓取糗事百科前10頁并存儲進數(shù)據(jù)庫示例

標簽:安康 長沙 山西 崇左 喀什 海南 山西 濟南

巨人網(wǎng)絡(luò)通訊聲明:本文標題《Ruby on Rails框架程序連接MongoDB的教程》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    封丘县| 磐安县| 剑川县| 武功县| 关岭| 县级市| 威远县| 平邑县| 黔南| 南岸区| 正蓝旗| 策勒县| 新田县| 清水河县| 丹寨县| 紫阳县| 额尔古纳市| 策勒县| 廊坊市| 和顺县| 罗城| 马边| 临夏市| 化隆| 广元市| 南澳县| 安吉县| 义乌市| 晋州市| 铜川市| 淄博市| 庄河市| 镇坪县| 弋阳县| 孝义市| 筠连县| 德惠市| 会理县| 乌恰县| 西吉县| 绵阳市|