Handling default values in models

You can do it by passing default parameters to the model on new. You
can push this down from the controller to the model as a method if you
want, e.g.

@user=User.new_with_defaults

The view will then pick up the defaults.

or if you want to make sure that the defaults are in place in all
places where a new object might be used then stick the code in
'after_initialize'.

If you need to do some calcs then there is always
'before_validation_on_create' or just 'before_create'. If you need to
do the calcs all the time then 'before_save'.

It depends what you're trying to achieve.

What you don't do is rely upon defaults in the database. For me the
default calculations have to be in the model.

Neil Wilson wrote:

It depends what you're trying to achieve.

For now, I wish to provide a simple, explicit, and model-centric means
of specifying default values for certain table attributes. Since I
posted above I have installed the active_record_defaults plugin and this
seems to provide most of what I desired.
For example:

Class MyTable < ActiveRecord::Base

  belongs_to :my_other_table

  # code dependent on active_record_defaults plugin
  default :effective_from => Time.now
  defaults :my_attribute => "unknown", :my_int_attribute => 21

  validates_presence_of :another_attribute

What you don't do is rely upon defaults in the database. For me the
default calculations have to be in the model.

My practice is that default values are mostly, if not entirely,
localized to the model or constrained within the DB schema. I depart
from Rails orthodoxy on this issue and I selected my database backend
(postgresql) with care so that significant amount of data integrity
logic could be enforced by the database.

For development I want this sort of stuff close to the code so that I
can easily adjust things without having to alter the DB overmuch. In
production I anticipate that a good deal of the constraints and defaults
will be moved from the model into the DBMS. Calculated fields are a
distinct issue, as you point out, and on that matter the model indeed
may be the best (perhaps only) place for them.

Thanks,