发布于 2015-09-14 15:02:20 | 136 次阅读 | 评论: 0 | 来源: 网络整理
Using Rails 3? See Rails 3 - Getting Started.
This tutorial describes how to set up a simple Rails application with MongoDB, using MongoMapper as an object mapper. We assume you’re using Rails versions prior to 3.0.
All of the configuration steps listed below, and more, are encapsulated in this Rails template (raw version), based on a similar one by Ben Scofield. You can create your project with the template as follows:
rails project_name -m <http://gist.github.com/219223.txt>
Be sure to replace project_name with the name of your project.
If you want to set up your project manually, read on.
We need to tell MongoMapper which database we’ll be using. Save the following to config/initializers/database.rb:
MongoMapper.database = "db_name-#{Rails.env}"
Replace db_name with whatever name you want to give the database. The Rails.env variable will ensure that a different database is used for each environment.
If you’re using Passenger, add this code to config/initializers/database.rb.
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
MongoMapper.connection.connect_to_master if forked
end
end
Clean out config/database.yml. This file should be blank, as we’re not connecting to the database in the traditional way.
Remove ActiveRecord from environment.rb.
config.frameworks -= [:active_record]
Add MongoMapper to the environment. This can be done by opening config/environment.rb and adding the line:
config.gem 'mongo_mapper'
Once you’ve done this, you can install the gem in the project by running:
rake gems:install
rake gems:unpack
It’s important to keep in mind that with MongoDB, we cannot wrap test cases in transactions. One possible work-around is to invoke a teardown method after each test case to clear out the database.
To automate this, I’ve found it effective to modify ActiveSupport::TestCase with the code below.
# Drop all columns after each test case.
def teardown
MongoMapper.database.collections.each do |coll|
coll.remove
end
end
# Make sure that each test case has a teardown
# method to clear the db after each test.
def inherited(base)
base.define_method teardown do
super
end
end
This way, all test classes will automatically invoke the teardown method. In the example above, the teardown method clears each collection. We might also choose to drop each collection or drop the database as a whole, but this would be considerably more expensive and is only necessary if our tests manipulate indexes.
Usually, this code is added in test/test_helper.rb. See the aforementioned rails template for specifics.
If you’ve followed the foregoing steps (or if you’ve created your Rails with the provided template), then you’re ready to start coding. For help on that, you can read about modeling your domain in Rails.