Rails

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"
  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:


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


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts