Migrate Away your Cruft

Last summer I developed my first Rails application under a very tight deadline. I cut a few(!) corners and one was not creating a link from my Person table to my Team table for the team coach.

So I’m trying to clean up after myself a bit. It turns out that I can get about 90% of the way there for just a few quick lines of code:

class AddFieldsToTeam < ActiveRecord::Migration
  def self.up
    add_column :teams, :coach_id, :integer
    add_column :teams, :asst_coach_id, :integer

    Team.reset_column_information

    @teams = Team.find(:all)
    @teams.each do |t|
      c = Person.find_by_full_name t.coach
      ac = Person.find_by_full_name t.asst_coach
      if !c.nil? || ac.nil?
        t.coach_id = c.id unless c.nil?
        t.asst_coach_id = ac.id unless ac.nil?
        t.save
      end
    end
  end

  def self.down
    remove_column :teams, :coach_id
    remove_column :teams, :asst_coach_id
  end
end

Here’s the findby_fullname:

  def self.find_by_full_name(fn)
    name = fn.split
    find(:first, :conditions => ["void = 0 and first_name = ? and last_name = ?", name.first, name.last])
  end

That’s just too easy.