Shawn Lindsey

ActiveRecord outside a Rails application

Active Record is the main tool that Rails developers use to communicate with and underlying database.  All Rails developers should be familiar with the Ruby programming language.  Active Record does some wonderful things for a web developer looking for abstractions in  database setup, SQL connections and queries.  You can get a command line Ruby application using Active Record going in about 5 minutes!

Active Record works great as a stand alone Ruby gem and it is simple to get going. Here is a quick guide to using Active Record in a standard Ruby application.

Gem install activerecord

You probably already have this one as a rails developer.  If you are a Ruby programmer just looking for database abstraction you will need to install the Active Record gem.


Require 'activerecord'

At the top of your Ruby program you need to require the Active Record gem previously installed.  Interacting with your database will be a pleasure now!

Establish a connection to your database

You now need to configure your connection.  This config will depend on the database you are using.  Once your connection is established all communications are database independent.  If your underlying database changes you will only need to change this configuration and everything in your application will still work!

ActiveRecord::Base.establish_connection {

  :adapter => "mysql"
  :host => "localhost"
  :username => "root"
  :password => "pword"
  :database => "dbname"
}


Create a database

Create a database for your application.  This code will first check that we have not already created this database. If your database does not exist yet it will create it.

unless TableName.table_exists?
  ActiveRecord::Schema.define do
    create_table "Table", :force => true do |t|
      t.string "data1"
      t.datetime "created_at"
      t.datetime "updated_at"
    end
  end
end


Add some columns to your database

You should now populate your database with some columns to store your data.


Viola! Use your database.

You now have a connection and have build a database to interact with.

Active Record is a great way to build quick Ruby applications that need a database.  With about 25 lines of code you can create a database, establish a connection, and add columns.  Add some rows of data now!

 

Shawn Lindsey

Categories

Other Posts

RSS Feed

Subscribe

Archives