ActiveRecord Without Rails

Some of you must be wondering, I must be insane to use ActiveRecord outside of Rails. But there are some very compelling reasons.

  • ActiveRecord is an awesome library for Object Relational Mapping (ORM).
  • Other projects might not involve the use of Rails.
  • You want to experiment with ActiveRecord prior to creating a plugin for your Rails project.
  • A library for ORM is already written (why reinvent the wheel?)
  • Your just very bored.

Whatever the case may be, it’s best to be prepared.

Installing ActiveRecord

If you already have Rails installed via RubyGems, then your already set to go. Else install it in the terminal via:

sudo gem install activerecord

Playing with ActiveRecord

Open up a file, and insert the following:

require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql',
  :database => 'database',
  :username => 'user',
  :password => 'password',
  :host     => 'localhost')

Now if you are familiar with Rails, this is the same configuration as seen in your database.yml file ( RAILS_ROOT/config/database.yml File). There are more options for how to connect to a database, just check the ActiveRecord::Base.establish_connection documentation.

Moving Database Configuration to Another File

Note: It’s not safe to save your database configuration in the same file as you code. In case you distribute your code, and forget to remove your password. That wouldn’t be a cool scenario. (Well it would also be pointless if you sent your database configuration file as well).

So lets make a database.yml and dump the information in there.

adapter: mysql
database:  database
username: user
password: password
host:      localhost

Now our previous file that utilizes ActiveRecord will look like such:

require 'rubygems'
require 'active_record'
require 'yaml'

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

Playing with ActiveRecord Safely!

And now your set to playing around with ActiveRecord without Rails!

require 'rubygems'
require 'active_record'
require 'yaml'

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

class User < ActiveRecord::Base
end

puts User.count
# 6

Debugging ActiveRecord SQL Queries

Sometimes you run into problems, and suspect your SQL isn’t generated as it’s supposed to be. But how do we debug this?

require 'rubygems'
require 'active_record'
require 'yaml'
require 'logger'

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)
ActiveRecord::Base.logger = Logger.new(STDERR)

class User < ActiveRecord::Base
end

puts User.count
# SQL (0.000277)   SELECT count(*) AS count_all FROM users
# 6

This will output it to standard error (in which most cases its) your screen. Sadly this can also clutter your screen.

Debugging ActiveRecord SQL Queries to a File

Now if you know your shell well, you can pipe it to a file via:

ruby connect.rb 2&gt;&gt; database.log

But you may forget to pipe it, or what not.

So replace the line containing ActiveRecord::Base.logger with

ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))

Warning: I chose to append (‘a’) the output to the file. This may result in very large files. You can chose to use overwrite (‘w’) instead.

From here on you can watch the file with: tail -f database.log [image16x16:terminal].

Funky/Colorized Logs

Note: If you view the database.log file, you’ll notice the following. This is because ActiveRecord colorizes output for viewing in a terminal. But when viewed as a normal file, you get garbage.

  ^[[4;36;1mSQL (0.000273)^[[0m   ^[[0;1mSELECT count(*) AS count_all FROM users ^[[0m

To disable colorize logging, enter:

ActiveRecord.colorize_logging = false

Translations

This article is translated to Serbo-Croatian language by Anja Skrba from Webhostinggeeks.com.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

16 Responses to ActiveRecord Without Rails

  1. jyu says:

    how could I know if the connection to sqlite database success

  2. salym says:

    thanks a lot man, this is exactly what i was looking for.

  3. weiwei5987 says:

    nice~~

  4. Shadley says:

    Hi, have you tried to get ActiveRecord Observers to work correctly outside of Rails?

  5. brent says:

    Help if you can, i cant get has_many to work i must be missing somthing

    #!/usr/bin/ruby

    require ‘rubygems’
    gem ‘activerecord’

    require ‘sqlite3′
    require ‘active_record’

    ActiveRecord::Base.establish_connection(
    :adapter => ‘sqlite3′,
    :database => ‘test.db’
    )

    class User < ActiveRecord::Base
    has_many :problems
    end

    class Problem < ActiveRecord::Base
    belongs_to :users
    end

    def show_single_item
    pr = Problem.find(:first)
    puts "showing first problem from the db below", pr.desc
    end

    def show_all_items
    pr = Problem.find(:all)
    puts "showing all problems from the db below"

    pr.each do |a|
    puts a.desc
    end
    end

    def check_has_many
    user = User.find(:first)
    puts user.problem.desc
    end

    # run some methods
    show_single_item # works
    show_all_items # works
    check_has_many # not working

  6. Pingback: Connect rails to existing postgres DB – models not seen by console and controllers | PHP Developer Resource

  7. Michael Gonzalez says:

    You are my f*cking hero!

    I’ve been looking to do a non-rails standalone ruby app, and wanted to use the ORM, but am still relatively new to ruby. This saved me a lot of time and headache!

    Thank you!

  8. PunctuationNazi says:

    “Your just very bored.”
    your != you’re

  9. Mandrake says:

    Nice article man!
    Great job thx!

  10. Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

  11. mondher says:

    Hi Aizat,

    Thanks for this useful article.
    I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module:
    module SqlHunter
    class ActiveRecord::ConnectionAdapters::AbstractAdapter

    @@queries = []
    cattr_accessor :queries
    def log_info_with_trace(sql, name, runtime)
    return unless @logger && @logger.debug?
    @@queries << sql
    end
    alias_method_chain :log_info, :trace
    end
    end

    in the controller I wrote that

    sqlfile = File.open("public/advancedStats/#{@dir_name}/advancedStatQuery.sql", 'w')
    @queries = ActiveRecord::ConnectionAdapters::AbstractAdapter::queries
    for query in @queries do
    sqlfile.write("#{query} \n")
    end
    sqlfile.close

    I also modified Rails environment by adding this line:

    ActiveRecord::Base.logger.level = Logger::DEBUG

    This program is working and I can get queries but, all queries. In contrast I need only the specific queries done by one user to generate a stat report.

    Do you have any idea to fix that,
    Thanks,

    mgatri

  12. Claudio says:

    I cant express the aewsome, thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>