Skip to content
naaano edited this page Apr 25, 2012 · 4 revisions

How to set default values to new records

Active Scaffold use default values in new records the same way any active record model does, that is, using defaults defined in database. However, sometimes you need something more flexible than altering database or add some logic to it.

By following advice from Jeff Perrin at stackoverflow, you may use after_initialize from active record:

class Person
    has_one :address
    after_initialize :init

    def init
      self.number  ||= 0.0           #will set the default value only if it's nil
      self.address ||= build_address #let's you set a default association
    end
end 
Clone this wiki locally