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.
migration rails
January 20th, 2006 05:55
Hey Tom,
The docs for migrations recommend a call to Base#resetcolumninformation after adding columns if you then need to populate them. Like you, I’ve found it’s not always necessary, but I reckon it’s good to get into the habit, especially if future versions of Rails cache more information than currently.
Just add ‘Team.resetcolumninformation’ after your add_column lines and you’re covered.
January 20th, 2006 06:06
Ah – I see you’ve got some markup codes running in your comments; sorry.
The method should, of course, be
reset_column_information.January 21st, 2006 06:00
Hi Scott,
Thanks for the pointer – I’ve updated the migration. One of those things that’s good to do even when it works otherwise.
Thanks!