In front of the introduction of the installation of MongoDB and ROR project construction, now to integrate.
1. Create a project
Do not use rails Active_record support when creating projects
2. We're going to use Mongomapper to drive MongoDB to rails
Edit Gemfile, add the following
Then perform the bundle install installation gem
3. Add Database Links
Under Config/initializer, create a new MONGO.RB file that specifies global database information:
Mongomapper.connection = mongo::connection.new (' localhost ', 27017)
mongomapper.database = ' Todo ' # By specifying rails to run environment parameters, we can create data that does not interfere with each other in a different running environment, and for simplicity, no different data is assigned to different environments
If defined? (Phusionpassenger)
Phusionpassenger.on_event (: starting_worker_process) do|forked|
MongoMapper.connection.connectifforked
End
After completing the steps above, start the program:
**NOTICE:C extension not loaded. This is required a for optimum MongoDB Ruby driver performance.
You can install the extension as follows:
If you are continue to receive this message over installing, make sure that the
bson_ext gem are in your load path and tha T 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 wit H-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
You can see from the above output that the Bson_ext library is not loaded. Follow the prompts to install the library (don't forget to add a gem to the Gemfile):
Start the program again, notice prompts the message to disappear, start normal. In the browser input: http://127.0.0.1:3000, you can see the following page
4. Add page and process logic
Generate pages, controllers, and model-level files through rails ' generate commands (individuals still like to create them manually, here for demonstration purposes)
Rails Generate Scaffold Project name:string--orm=mongo_mapper
Because we use MONGO as a database. Then, we need to change the model of ActiveRecord to Mongomapper type, that is, to transform the inheritance relationship from ActiveRecord::Base to Mongomapper::D ocument. We use the key method to indicate the field properties of the Mongomapper. Our property is name, plus the type string for this field, and the definition is as follows:
Classproject
include Mongomapper::D ocument
key:name,string
End
With the above modifications, we already have all the additions, updates, deletes, and list operations.
5. Data viewing
Queries that can be entered into the MongoDB database by command MONGO
MONGO//Enter database use
TODO//switch library
db.projects.find ()//Execute Query
Mongomapper and ActiveRecord are exactly the same. Even, Mongomapper still supports the ActiveRecord authentication method as follows
Validates_presence_of:name
Since MongoDB does not have a schema-less (data version record) we can easily add and change the properties of model without having to perform any migrations operations. For example, we need to add a priority attribute, we just need to modify project model as follows:
Classproject
include Mongomapper::D ocument
key:name,string,:required=>true
Key:priority,integer End
The association between tables is slightly different for MongoDB, and we need a Objectid type to store all IDs.
As for dealing with the associations before different tables, we can define belongs_to like ActiveRecord, and of course, a little bit differently, in project we need to define has_many:tasks, and in Mongomapper we need many instead.
I'm doing it right now. Have time to delve into other functions.
Ps:ruby Write MongoDB backup script (Fsync & Lock)
#!/usr/local/bin/ruby # date:06-12-2014 # auther:lucifer # Use Fsync & lock to the File-system before backup the F Ile-system # Mongo-ruby-driver version > 1.10.0 require ' MONGO ' require ' fileutils ' require ' date ' include MONGO incl Ude Bson # The members of Replcation-set # Test MongoDB server version 2.6.0 # host = ' 192.168.11.51 ' # The Port of Memb ERS # If The port is 27017 by default then Otherport don ' t need to assignment # Otherport = "" # port = otherport.length! = 0? Otherport:mongoclient::D Efault_port # opts = {:p ool_size => 5,:p ool_timeout =>} # Create A new Connection # C Lient = mongoclient.new (host, Port, opts) uri_string = "mongodb://caoqing:xxxxxxxx@x.x.x.x:27017/admin" client = MongoCl Ient.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}" Fil EUTILS.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 "*" * puts "\tbackup complete" puts "*" * * db::system_command_collection # Unlock the database db["$cmd. sys.u
Nlock "].find_one Client.close