Blog An exploration of the art and
craft of software development

ActiveRecord change_column

Posted by Marty Haught on Saturday, February 23, 2008
Yesterday I needed to perform a migration to change some of the attributes on a database column. Specifically we decided to add a default value and set a not null constraint on it. It was already defined and had important data in several databases. I wanted to do it in a ruby way but didn't feel that adding and removing a column was acceptable. I was hoping I didn't have to drop to native SQL to do an alter command. Luckily after a bit of searching through the API I stumbled across the change_column method in ActiveRecord. This was exactly wanted I needed but I had never heard it referenced before. I'm sure to many this is obvious and perhaps they've used it many times before. Since it may save some others some time, I'll just do a fast post about it. Here's an example of how we used it:
  def self.up
    change_column :my_table, :handling_fee, :decimal,  :precision => 5, :scale => 2, 
      :default => 0.0, :null => false
  end

  def self.down
    change_column :my_table, :handling_fee, :decimal,  :precision => 5, :scale => 2
  end

Enjoy!

blog comments powered by Disqus