Self in before_create

Hi, I am having a small problem concernig how to access local variables
in
before_create. I am not sure how to really form this question but here
goes:

I am wondering why this works

def before_create
self.last_logged_in = Time.now
self.created = Time.now
end

but this doesn’t

def before_create
@last_logged_in = Time.now
@created = Time.now
end

The latter fails with the following error:

Mysql::Error: #23000Column ‘last_logged_in’ cannot be null:

On Tue, Feb 14, 2006 at 06:29:16PM +0000, Bjarki Gudlaugsson wrote:

but this doesn’t

def before_create
@last_logged_in = Time.now
@created = Time.now
end

I don’t think this is a before_create-specific problem. In general, the
database fields in an AR object aren’t just instance variables –
they’re
actually values in the @attributes (from memory) instance variable. So
you’d need to do

def before_create
@attributes[‘last_logged_in’] = Time.now
@attributes[‘created’] = Time.now
end

But, of course, that’s a damn sight longer than self., so
stick
with that.

On another optimisation point, if you create a field in your database
called
‘created_at’, AR will automatically fill that field out with Time.now at
object creation time, which will save you a couple of lines of code here
and
there.

  • Matt