Tutorial on Ruby on Rails Framework Program connecting to MongoDB, railsmongodb

Source: Internet
Author: User
Tags mongoclient mongodb server

Tutorial on Ruby on Rails Framework Program connecting to MongoDB, railsmongodb

We will introduce mongodb installation and setup of the ror project in the front. Now we will integrate it.

1. Create a project

Rails active_record support is no longer used when creating a project

rails new todo -O
2. We are going to use MongoMapper to drive MongoDB to Rails

Edit GemFile, add the following content

gem "mongo_mapper"
Then execute bundle install to install the gem

bundle install
3. Add a database link

Create a new mongo.rb file under config / initializer and specify global database information:

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


MongoMapper.database = 'todo' # By specifying Rails operating environment parameters, we can create data that does not interfere with each other in different operating environments. For simplicity, we did not specify different data for different environments

if defined? (PhusionPassenger)

  PhusionPassenger.on_event (: starting_worker_process) do | forked |

    MongoMapper.connection.connectifforked

  end

end

After completing the above steps, start the program:

$ 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

From the above output, you can see that the bson_ext library is not loaded. Follow the prompts to install the library (do n’t forget to add the gem to the gemfile):

Start the program again, the Notice message disappears, and the startup is normal. Enter in the browser: http://127.0.0.1:3000, you can see the following page

4. Add pages and processing logic

Generate the page, controller and model layer files through the generate command of rails (personal still prefer to create it manually, here for demonstration convenience)

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

Since we use mongo as the database. Then, we need to change the ActiveRecord model to the type of MongoMapper, which is to change the inheritance relationship from ActiveRecord :: Base to MongoMapper :: Document. We use the key method to indicate the field properties of the MongoMapper. Our property is name, plus the type String of this field, then the definition is as follows:

classProject

  include MongoMapper :: Document

  key: name, String

end

Through the above modifications, we already have all the operations of adding, updating, deleting and listing

5. Data viewing

You can enter the mongodb database to query data through the command mongo

mongo // Enter the database

use todo // Switch library

db.projects.find () // Execute query


6. Other
MongoMapper and ActiveRecord are identical. Even, MongoMapper still supports ActiveRecord verification method as follows

validates_presence_of: name
Since MongoDB has no schema-less (data version records), we can easily add and change model attributes without performing any migrations. For example, we need to add a priority attribute, all we need is to modify the Project model as follows:

classProject

  include MongoMapper :: Document

  key: name, String,: required => true

  key: priority, Integer

end

The association between the tables is slightly different for MongoDB here, we need the ObjectId type to store all ids.

As for handling associations before different tables, we can define belongs_to like ActiveRecord. Of course, it is a little different. In Project, we need to define has_many: tasks, which needs to be replaced by many in MongoMapper.

I will do it right now. Have time to delve into other features.

PS: Ruby writes MongoDB backup script (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 ("# {d}")
# 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 ("# {d} / **"), 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.