Apr 10 2010

Activerecord file fun

Published by Rudy Godoy at 3:50 pm under htu

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
#!/usr/bin/ruby

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

# Let AR know who is working with!
ActiveRecord::Base.establish_connection(
: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
end

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

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

View Comments

  • tabo
    It looks very fragile. In SQL, queries without an ORDER BY are non-deterministic, so there is no real guarantee that you'll get the same ordering every time you run a plain SELECT.

    You're lucky Murphy didn't knocked your door again ;)
  • Yes, I took my chances :) had the data isolated (no read/write activity
    from anyone else). You can get deterministic results in MySQL, for instance,
    using store procedures, but that's another story.
blog comments powered by Disqus