Wednesday, August 19, 2009

Setting/Changing ActiveRecord Default Values

The default value of an attribute in an ActiveRecord object can (often) come from the default value that it sets in the definition of the column of the table in the database.

Let's say that you have a migration where you add a new column and set a default:

  def self.up
    add_column :books, :author, :string, :default => 'Anonymous'
  end

  def self.down
    remove_column :books, :author
  end

After you run this migration all of the previous records in the table 'BOOKS' will not only have a new 'AUTHOR' column, but also the column definition for 'AUTHOR' will have a default value of 'Anonymous'.

If you want to change the default value of that column (for future records that are created), you can do that via another migration:

  def self.up
    change_column :books, :author, :string, :default => 'John Doe'
  end

  def self.down
    change_column :books, :author, :string, :default => 'Anonymous'
  end

Note that you have to specify the type, even though the type has not changed.

For more information on setting defaults for ActiveRecord objects, see stackoverflow:
* http://stackoverflow.com/questions/328525/what-is-the-best-way-to-set-default-values-in-activerecord

No comments: