[Rails] Re: how do set default value for ActiveRecord fields?

Caio Chassot
Tue, 01 Aug 2006 13:59:19 -0000

On 2006-08-01, at 10:02 , Simon wrote:

> Chris wrote:
>> So when you create a new activerecord instance (before you save
>> it) does
>> it look to see what the default value is from the schema?
>>

It does. That''s also why you can''t have expressions as
defaults (eg.
NOW()), just literals.

>> I want the default value to be assigned upon creation of the object,
>> i.e. Record.new, and not when it gets saved.

Yep. Rails will look it up, it''ll be set at instantiation.

> Set the default value in the controller.

Bad idea. Let the model handle it.

I''m thinking about writing a plugin that initializes default values.
It''s useful when you have more complex defaults, e.g. with
inheritance, that each descendant model may have a different default
for the same field. Sintax would be something like

   class Post < AR...
     defaults :title => ''(untitled)'', :status =>
''unpublished'',
       :whatever => lambda { |record| ... some dynamic magic ... }
   end

You can also do similar just by overriding the accessors.