Daily ArchiveThursday, January 19th, 2006
Uncategorized 19 Jan 2006 09:56 pm
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
Note to self 19 Jan 2006 08:34 pm
How to set ENV for rake migrate
If you’re running a recent rails app and are on a host like DreamHost where the RAILS_ENV isn’t set, you’ll need to use this to run your migrations:
rake environment RAILS_ENV=production migrate
Otherwise you’ll get this:
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
Or you’ll connect to your development database if you have one configured.