Using ActiveRecord with Rails

Here’s an example of using ActiveRecord without Rails.  Ideally, this should be done with a migration, which will be the subject of my next post.  However, first the basics. As before, replace [username] and [password] with the username and password associated with your database (“Test”, in my case).

require 'active_record'

# Note that the class doesn't define any properties
class User < ActiveRecord::Base
end

class ActiveRecordTest
  # Create a connection.
  def connect
    ActiveRecord::Base.establish_connection(
        :adapter => "postgresql",
        :username => "[username]",
        :password => "[password]",
        :database => "Test")
  end

  # Create the users table.
  def createUserTable
    ActiveRecord::Migration.create_table :users do |t|
      t.integer :id
      t.string :name
      # or
      # t.column :id, :integer
      # t.column :name, :string
    end
  end

  # Drop the users table.
  def dropUserTable
    ActiveRecord::Migration.drop_table :users
  end

  # Add a user.
  def addUser(id, username)
    user = User.new
    user.id = id
    user.name = username
    user.save
  end

  # Query the user table, allowing the caller to handle the returned User records.
  def queryUserTable
    User.all.each {|user| yield user}
  end

end

def main
  ar = ActiveRecordTest.new
  ar.connect
  ar.createUserTable
  ar.addUser(1, "Marc")
  ar.addUser(2, "Sharon")
  ar.queryUserTable {|user| printf("%d %s\n", user.id, user.name)}
  ar.dropUserTable
end

main
Advertisements

One thought on “Using ActiveRecord with Rails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s