Default value for model var


#1

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.


#2

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.


#3

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


#4

That’s exactly what I was looking for. Thanks!