Tuesday, June 10, 2008

ActiveRecord requires RAILS_ROOT for relative Sqlite path

I'm writing a little time tracking tool for Windows in Ruby. The data is stored in a database so I figured I'd use ActiveRecord and maybe learn something about Rails along the way. Everything I found about ActiveRecord tells me that it "can be used independently outside of Rails". One minor detail that I just figured out:
If you want to use a relative path for a sqlite3 database in your database.yml, you have to define RAILS_ROOT.
For example, if config/database.yml =>
  1. production:  
  2.   adapter: sqlite3  
  3.   database: db/production.sqlite  
ActiveRecord initialization (mine's in config/boot.rb) looks like:
  1. RAILS_ROOT = "#{File.dirname(File.expand_path(__FILE__))}/.."  
  2. RAILS_ENV  = ENV['RAILS_ENV'] || 'production'  
  3.   
  4. $LOAD_PATH.unshift "#{RAILS_ROOT}/vendor/sqlite3"  
  5. config = YAML::load(IO.read("#{RAILS_ROOT}/config/database.yml"))  
  6. ActiveRecord::Base.configurations = config  
  7. ActiveRecord::Base.establish_connection(config[RAILS_ENV])  

No comments :

Post a Comment