Notes on migrations

Posted by topher
on Tuesday, November 13

If you add columns to a model, and you want to use that model, call Base#reset_column_information.

If you save a model in a migration, and if you do not want the timestamps (created_at, updated_at) to be updated, put ActiveRecord::Base.record_timestamps = false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class AddLastCommentAtToTopic < ActiveRecord::Migration
  class Topic < ActiveRecord::Base
    has_many :posts
  end
  
  class Post < ActiveRecord::Base
  end
  
  def self.up
    ActiveRecord::Base.record_timestamps = false
    add_column :topics :last_comment_at, :datetime
    Topic.reset_column_information
    Topic.find(:all).each do |topic|
      topic = topic.posts.find(:first, :order => "last_comment_at DESC")
      if topic
        topic.last_comment_at  = post.last_comment_at
        topic.save
      end
    end
    ActiveRecord::Base.record_timestamps = true
  end

  def self.down
    remove_column :topics, :last_comment_at
  end
end