Forum: Ruby on Rails How to handle default database values now?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Joe (Guest)
on 2006-04-27 00:41
Since interpreting defaults in the database has been ripped out (for
PostgreSQL at least), what's the standard way of specifying defaults
now?

Right now, I'm doing this:

# model

def create
  self.datetime = Time.now

  super
end


I hate it. I know there are the '*_at/on' automatic fields, but that'll
entail combing through all my code changing field names. I hate that
too.

Joe
Alex W. (Guest)
on 2006-04-27 01:12
Rather than "create", setup the defaults in "intialize".  You get the
most bang for your buck this way since every new record will execute
that method regardless of how its created.  I would do it like this:

  DEFAULTS = {
    :datetime => Time.now,
    :some_other_field => 'foo'
  }

  def initialize
    self.attributes = DEFAULTS
  end

Then you can do

  Model.new
  Model.create(params[:model])
  Parent.models.create(params[:model])

And they all will have the proper values in it.



Joe wrote:
> Since interpreting defaults in the database has been ripped out (for
> PostgreSQL at least), what's the standard way of specifying defaults
> now?
>
> Right now, I'm doing this:
>
> # model
>
> def create
>   self.datetime = Time.now
>
>   super
> end
>
>
> I hate it. I know there are the '*_at/on' automatic fields, but that'll
> entail combing through all my code changing field names. I hate that
> too.
>
> Joe
This topic is locked and can not be replied to.