Activerecord file fun

For those who doesn’t know Activerecord is a software design pattern, not only an implementation.

Sometimes you are in a middle of a rush and Mr. Murphy knocks your door. I had such case: Customer imported user emails with a misspelling, asked for help. I tried to exercise my SQL skills in a bad way, Murphy steps in. Fortunately we have tools for fixing things.

Activerecord is an approach for database access, it’s based in OOP concepts and basically maps a record as a class. Thus, you can treat each record as standard objects, this means (for the lazy) that you can do things like attribute update.

So, back on the case. I wrote a simple piece of code using Ruby on Rails AR implementation. What it does? It saves my job, filename says it all (for the es_PE speaking people). It uses the email addresses from the file to update the email column in the database for each user.

Note: This case only works for 1:1 matching situation. If the list is sorted somehow different than the records, things will go wrong. However I post it here for educational purposes. I’ve commented the code acoordingly. Enjoy and comment.

cat recon.rb

# Imports rubygems classes and then active record
require 'rubygems'
require 'active_record'

# Let AR know who is working with!
:adapter => 'mysql',
:host => 'localhost',
:database => 'app',
:username => 'user',
:password => 'secret'

# Map table as a AR class.
# Note that I had to set the table name, since my database didn't use AR naming convention, so I had to also set primary key.

class User < ActiveRecord::Base
set_table_name :user
set_primary_key :user_id

# Open the lucky file.
f ="emails.txt")
# Update each record thanks to AR properties. Yay!
User.find(:all).each do |u|
u.update_attribute :email, f.gets.chomp

# Just check if it did the job.
puts "check"
uc = User.find(:all)
uc.each do |usr|
puts "#{usr.username} : #{}"