Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

ActiveRecord and SQL Server (See related posts)

From http://www.softiesonrails.com/articles/2006/06/28/activerecord-with-sqlserver-without-rails:

Ensure you done the initial setup for SQL Server and ActiveRecord (ADO.rb).

require 'rubygems'
require_gem 'activerecord'

ActiveRecord::Base.establish_connection(
  :adapter  => "sqlserver",
  :dsn => "instance_name_goes_here",
  :host => "machine_name\\instance_name",
  :database =>  "db_name",
  :username =>  "my_username",
  :password =>  "my_password"
)

class MsSqlTable < ActiveRecord::Base
  def method_missing(method, *args)
    respond_to?(method) ? super : send(method.to_s.camelize, *args)
  end
end

class Item < MsSqlTable
  set_primary_key "sku"
  set_table_name "item"
end


I'll walk through it real quick:

1. The :dsn needs to be your SQL Server instance name
2. The :host needs to a path like "myserver\myinstance", even though you've already specified the instance name in the :dsn parameter
3. The rest of the settings should be obvious. If your password is blank, don't specify :password at all.
4. Our legacy column names are things like OldDescription. So I created an intermediate base class that would provide ruby-like aliases. Now I can use item.old_description instead if I want to.
5. Finally, I declare one class for each table I want to access. I have to set the primary key and table name manually, since our tables don't correspond to any Rails conventions.

I saved this script as legacy.rb, and then fired up irb from that directory:
irb> load 'legacy.rb'
=> true
irb> Item.find("191191").old_description
=> "Table In A Bag"
irb>

Comments on this post

dpk posts on Jul 19, 2006 at 21:29
I think this is a great idea, and one that I definately need. Unfortunately, I also need to have the cascading and have no idea what i'm doing in Ruby so there is no way I could expand on this (or even comprehend exactly what its doing). Is there any interest to make this into a full plugin with the cascading built in?
dpk posts on Jul 19, 2006 at 21:30
this is on the wrong post...whoops :-) I will repost it under the correct one

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts