• No results found

Rails - Getting Started

In document MongoDB Docs (Page 97-101)

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.

Configuration Testing Coding

Using a Rails Template

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.

Configuration

1. 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.

2. 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

3. Clean out config/database.yml. This file should be blank, as we're not connecting to the database in the traditional way.

4. Remove ActiveRecord from environment.rb.

config.frameworks -= [:active_record]

5. 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

Testing

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.

Coding

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.

Rails 3 - Getting Started

It's not difficult to use MongoDB with Rails 3. Most of it comes down to making sure that you're not loading ActiveRecord and understanding how to use Bundler, the new Ruby dependency manager.

Install the Rails 3 Configure your application Bundle and Initialize

Bundling Initializing Running Tests Conclusion See also

Install the Rails 3

If you haven't done so already, install Rails 3.

# Use sudo if your setup requires it gem install rails

Configure your application

The important thing here is to avoid loading ActiveRecord. One way to do this is with the --skip-active-record switch. So you'd create your app skeleton like so:

rails new my_app --skip-active-record

Alternatively, if you've already created your app (or just want to know what this actually does), have a look at config/application.rb and change the first lines from this:

require "rails/all"

to this:

require "action_controller/railtie"

require "action_mailer/railtie"

require "active_resource/railtie"

require "rails/test_unit/railtie"

It's also important to make sure that the reference to active_record in the generator block is commented out:

# Configure generators values. Many other options are available, be sure to check the documentation.

# config.generators do |g|

# g.orm :active_record

# g.template_engine :erb

# g.test_framework :test_unit, :fixture => true

# end

As of this this writing, it's commented out by default, so you probably won't have to change anything here.

Bundle and Initialize

The final step involves bundling any gems you'll need and then creating an initializer for connecting to the database.

Bundling

Edit Gemfile, located in the Rails root directory. By default, our Gemfile will only load Rails:

gem "rails", "3.0.0"

Normally, using MongoDB will simply mean adding whichever OM framework you want to work with, as these will require the "mongo" gem by default.

# Edit this Gemfile to bundle your application's dependencies.

source 'http://gemcutter.org' gem "rails", "3.0.0"

gem "mongo_mapper"

However, there's currently an issue with loading bson_ext, as the current gemspec isn't compatible with the way Bundler works. We'll be fixing that soon; just pay attention to this issue.

In the meantime, you can use the following work-around:

# Edit this Gemfile to bundle your application's dependencies.

require 'rubygems' require 'mongo'

source 'http://gemcutter.org' gem "rails", "3.0.0"

gem "mongo_mapper"

Requiring rubygems and mongo before running the gem command will ensure that bson_ext is loaded. If you'd rather not load rubygems, just make sure that both mongo and bson_ext are in your load path when you require mongo.

Once you've configured your Gemfile, run the bundle installer:

bundle install

Initializing

Last item is to create an initializer to connect to MongoDB. Create a Ruby file in config/initializers. You can give it any name you want;

here we'll call it config/initializers/mongo.rb:

MongoMapper.connection = Mongo::Connection.new('localhost', 27017) MongoMapper.database = "#myapp-#{Rails.env}"

defined?(PhusionPassenger) if

PhusionPassenger.on_event(:starting_worker_process) do |forked|

MongoMapper.connection.connect if forked end

end

Running Tests

A slight modification is required to get rake test working (thanks to John P. Wood). Create a file lib/tasks/mongo.rake containing the following:

namespace :db do namespace :test do task :prepare do

# Stub out for MongoDB end

end end

Now the various rake test tasks will run properly. See John's post for more details.

Conclusion

That should be all. You can now start creating models based on whichever OM you've installed.

See also

Rails 3 App skeleton with MongoMapper Rails 3 Release Notes

In document MongoDB Docs (Page 97-101)