2

What's the proper way to set default values for models in Rails?

class User < ActiveRecord::Base
  attr_accessible :name, :points
end

I want points to start out at 0 instead of nil. Ideally the default value is created right away rather than waiting for the User to be saved into the database. But I guess using a before_save or database constraints work as well:

class User < ActiveRecord::Base
  attr_accessible :name, :points
  before_save :set_defaults

  private
  def set_defaults
    self.points = 0
  end
end

Using the latest stable Rails.

at.
  • 50,922
  • 104
  • 292
  • 461

2 Answers2

8

set it in your migration:

 t.integer :points, default: 0
m_x
  • 12,357
  • 7
  • 46
  • 60
0

You can set default value by migration or by using model setter methods.

change_column :user, :points, :integer, :default => 0

Or,

def points
    @points ||= 0
end
Manish Nagdewani
  • 597
  • 1
  • 3
  • 14