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 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 - Ruby / Rails

Date:March 18, 2015