Forum: Ruby on Rails Default value for model var

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.
Jonathan M. (Guest)
on 2006-06-12 23:25
(Received via mailing list)
I know this has got to be a really dumb question, but here goes anyway.

I've got a model with an associated table. One of the columns in the
table is 'date_created', which I want to be set to the date/time each
row was added to the table.

Seems to me that setting this in the initialize method for the model
would be the right thing to do,...

class MyThing < ActiveRecord::Base
  def initialize
    @date_created = DateTime.now
  end
...

But that throws other errors since the controller is calling the class
with additional arguments from the form entry that started the process.

@thing = MyThing.new(params[:thing])


I know I must be missing something pretty basic, but any help getting me
pointed in the right direction would be greatly appreciated.
Jonathan M. (Guest)
on 2006-06-12 23:41
(Received via mailing list)
I knew that as soon as I asked, I'd find the answer on my own.

created_at/created_on; Not exactly what I was looking for, but it'll
serve the purpose for now.

However, any info on the more general task of setting default values for
model variables would still be appreciated.
Philip H. (Guest)
on 2006-06-13 03:07
(Received via mailing list)
>  def initialize
> I know I must be missing something pretty basic, but any help getting me
> pointed in the right direction would be greatly appreciated.

You already found created_at/on and it's friend updated_at/on, but also
look into before_save() and before_create().

-philip
Jonathan M. (Guest)
on 2006-06-13 04:05
(Received via mailing list)
That's exactly what I was looking for. Thanks!
This topic is locked and can not be replied to.