ActiveRecord and SQL Server
Ensure you done the initial setup for SQL Server and ActiveRecord (ADO.rb).
1 2 require 'rubygems' 3 require_gem 'activerecord' 4 5 ActiveRecord::Base.establish_connection( 6 :adapter => "sqlserver", 7 :dsn => "instance_name_goes_here", 8 :host => "machine_name\\instance_name", 9 :database => "db_name", 10 :username => "my_username", 11 :password => "my_password" 12 ) 13 14 class MsSqlTable < ActiveRecord::Base 15 def method_missing(method, *args) 16 respond_to?(method) ? super : send(method.to_s.camelize, *args) 17 end 18 end 19 20 class Item < MsSqlTable 21 set_primary_key "sku" 22 set_table_name "item" 23 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:
1 2 irb> load 'legacy.rb' 3 => true 4 irb> Item.find("191191").old_description 5 => "Table In A Bag" 6 irb>