In this second part of my mini-series focused on Ruby on Rails applications running on OpenShift. In this post I will discuss setting up Ruby on Rails project leveraging MongoDB.
Ruby on Rails application
With the data backend being MongoDB, there is no need to have ActiveRecord available in you application. So, let's create new Rails application without ActiveRecord.
rails new mongorails --skip-active-record
Without ActiveRecord the application has no ORM to help with the Model layer. As MongoDB is a document oriented database it provides ODMs - Object-Document-Mappers. In this article I will be using Mongoid ODM.
Setting up Mongoid
To provide connection configuration Mongoid loads config/mongoid.yml file automatically.In this second part of my mini-series focused on Ruby on Rails applications running on OpenShift. In this post I will discuss setting up Ruby on Rails project leveraging MongoDB.
Ruby on Rails application
With the data backend being MongoDB, there is no need to have ActiveRecord available in you application. So, let's create new Rails application without ActiveRecord.
rails new mongorails --skip-active-record
Without ActiveRecord the application has no ORM to help with the Model layer. As MongoDB is a document oriented database it provides ODMs - Object-Document-Mappers. In this article I will be using Mongoid ODM.
Setting up Mongoid
To provide connection configuration Mongoid loads config/mongoid.yml file automatically. Let's create the file and add an OpenShift specific configuration for production environment.
production:
sessions:
default:
database: <%= ENV['OPENSHIFT_APP_NAME'] %>
hosts:
- <%= ENV['OPENSHIFT_MONGODB_DB_HOST'] || 'localhost' %>:<%= ENV['OPENSHIFT_MONGODB_DB_PORT'] || 27017 %>
username: <%= ENV['OPENSHIFT_MONGODB_DB_USERNAME'] %>
password: <%= ENV['OPENSHIFT_MONGODB_DB_PASSWORD'] %>
Configuring gems
The configuration is in place, let's modify Gemfile in the root of you application. To add the mongoid gem, use line as
gem 'mongoid'
Once edited, you need to bundle the gems to create updated Gemfile.lock
bundle install
Configuring an OpenShift gear with Ruby and MongoDB support
We now have our configuration complete. Now, let's create new OpenShift application:
rhc app create mongorails ruby-1.9
and embed the MongoDB cartridge into the application
rhc cartridge add mongodb-2.0 -a mongorails
and move the source code of the application into the repository OpenShift created for you locally. Commit the files to Git and push to OpenShift.
git add .
git commit -m "Initial commit"
git push origin master
Conclusion
That's it. You now have a Ruby on Rails application with MongoDB backend in the cloud, ready for your next big idea!