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.