Working with ActiveRecord model classes outside of the Rails environment

I had a task yesterday that involved me wanting to dump some information about a Rails ActiveRecord class I had (don’t ask, it’s a long story).

I wanted to access my AR class from outside the Rails web environment (i.e. I wanted to type ‘ruby something’ from the command line).

I put a file in the scripts folder and put the following code at the top:

ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || ‘development’
RAILS_ROOT = “#{File.dirname(__FILE__)}/..” unless defined?(RAILS_ROOT)
require ‘rubygems’
require ‘active_record’

ActiveRecord::Base.establish_connection(YAML::load(File.open(‘config/database.yml’))[ENV['RAILS_ENV']])

From here on out, you have the basics of the rails environment and can execute ActiveRecord functionality.

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    About Chad Myers

    Chad Myers is the Director of Development for Dovetail Software, in Austin, TX, where he leads a premiere software team building complex enterprise software products. Chad is a .NET software developer specializing in enterprise software designs and architectures. He has over 12 years of software development experience and a proven track record of Agile, test-driven project leadership using both Microsoft and open source tools. He is a community leader who speaks at the Austin .NET User's Group, the ADNUG Code Camp, and participates in various development communities and open source projects.
    This entry was posted in Rails, Ruby. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
    • Mike Breen

      What about creating a rake task? Then you could just type ‘rake something”?

    • http://chadmyers.lostechies.com chadmyers

      I hadn’t got that far yet, I wanted to be able to do it first before automating it. This was the first day I had done any Ruby at all, so take it easy on me :)

    • Mike Breen

      When you’re ready to write a custom rake task you should check out this tutorial: http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial

      Good luck!

    • Mike Breen

      I also like to think of rake as a tool for “heavy lifting” in Rails, not just automation. Getting at the Rails environment is easy enough:

      task(:my_task => :environment) do
      #work with you AR here
      end

      But I’m not sure what you’re trying to accomplish so maybe rake won’t help you here.