Skip to content

Instantly share code, notes, and snippets.

@schoblaska
Created January 13, 2009 19:14
Show Gist options
  • Select an option

  • Save schoblaska/46570 to your computer and use it in GitHub Desktop.

Select an option

Save schoblaska/46570 to your computer and use it in GitHub Desktop.
# This is a blog post I wrote almost two years ago. It was some of the first Ruby I ever uttered, and not
# entirely useful or elegant, but I'm reposting it now because I recently received a requst for it.
# Ruby on Rails: Working With a Legacy Database With a Non-Integer Primary Key
# For a project I'm currently working on, I needed to get my Rails application to work with a legacy
# database that used a non-integer primary key (in this case, a field called "loginID", which is basically
# a username). First, I tried to use "set_primary_key" to define my PK, but Rails was having none of that.
# Instead, I decided to write a couple of custom methods for my legacy class.
# To connect to the legacy database, I first added the following configuration to the end of my
# config/database.yml file:
# legacy database info
legacy_db:
adapter: mysql
database: legacy_database_name
username: user
password: pass
host: localhost
# Once my database credentials were defined, I set up my LegacyUser class to use the legacy_db
# connection, and wrote custom update and delete methods. The update method takes a hash, just
# like the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001044">ActiveRecord method
# update_attributes</a>. It goes through this hash and updates each attribute in the legacy database as
# appropriate.
class LegacyUser < ActiveRecord::Base
set_table_name "legacy_user_table"
establish_connection :legacy_db
validates_uniqueness_of :loginID
def update(var)
query = "UPDATE legacy_user_table SET "
query += var.keys.map{ |k| %%#{k.to_s} = "#{var[k]}"% }.join(", ")
query += %% WHERE loginID = "#{self.loginID}"%
LegacyUser.connection.execute query
end
def delete
LegacyUser.connection.execute %%DELETE FROM legacy_user_table WHERE loginID = "#{self.loginID}"%
end
end
# There may be a cleaner way to do this, but nothing I tried worked with this particular database.
# If you find yourself having to write some custom SQL functions as a last resort, hopefully this
# example will have given you a good place from which to start.
# As with most of the Rails things I do, thanks to <a href="http://www.napcsweb.com/">Brian Hogan</a>
# for helping me out with this.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment