Default Model Attributes In Rails

Posted by Weston Ganger on March 18, 2015

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"

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?

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:

Posted in Rails and Tagged with rails active-record callbacks ruby 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts