Default Model Attributes In Rails

Posted By Weston Ganger

Sometimes it is helpful to have default values for an attribute. You have two options when it comes to this
Option 1: Default value contraint in database:


class AddPublished < ActiveRecord::Migration
  def change
    change_column :posts, :description, :string, default: "My default value"
  end
end


Option 2: after_initialize callback:


class Post < ActiveRecord::Base
  after_initialize :set_defaults

  def set_defaults
    self.description = "My Default Value" if self.new_record?
  end
end

I added the if self.new_record? portion because after_initialize runs when building a new record or after fetching a record. I only want the value to be set on newly built records.

I think that Option 2 is more flexible but Option 1 has its perks too


Related External Links:

Article Topic:Software Development - Rails

Date:March 18, 2015