Skip navigation

Currently Being Moderated

Using ActiveRecord 3 without Rails

Posted by RobCameron.2.16b on Feb 28, 2011 1:12:55 PM

ActiveRecord is great but it can be a little scary to think about using it without Rails. Here's a quick example of using it with Sinatra.


The first thing we'll want to do is get the ActiveRecord gem by itself (throughout this tutorial I'm assuming you're using Bundler to manage your gems):


gem 'activerecord', :require => 'active_record'


Next up, in the configure block of our Sinatra app, we'll set up the AR connection to our database:


ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => 'db/development.db')


Of course, if you want to stay flexible, you can move your database config into a YAML file (laid out the same as the Rails standard config/database.yml file) and pull the connection details from that:


db_config = YAML::load(,'config','database.yml')))[Sinatra::Application.environment]

Now that AR is ready to go we can include our models. I like to move my models into separate files, similar to Rails's app/models, so I tell Sinatra to include every file in that directory:


Dir.glob('./app/models/*').each { |r| require r }


Believe it or not, that's really all you need to do to start using AR in your Sinatra application! The only missing link is database migrations. AR comes with a huge Rake file full of tasks like db:migrate, but unfortunately those rely on being inside the shell of Rails (they look for environment variables like RAILS_ENV and the base Rails object all over the place). Here's a very simple piece of code that will enable the standard db:migrate task:


require 'bundler'

desc "Migrate the database through scripts in db/migrate."
task :migrate do
  ActiveRecord::Base.establish_connection(YAML.load('config','database.yml')))[ENV['ENV'] ? ENV['ENV'] : 'development'])


This assumes that your migration files are in db/migrate. When you want to migrate in an environment other than development just set the ENV variable:


rake db:migrate ENV=production


That's it! There are a couple of different database ORM libraries out there besides ActiveRecord (like Sequel and Datamapper) but AR is the most popular today and it's easy to use it in all of your web apps, whether they're Rails or not.

Comments (0)