# Self in before\_create

**URL:** <https://www.ruby-forum.com/t/self-in-before-create/53855>\
**Category:** Rails\
**Created:** [February 15, 2006, 1:33pm UTC](https://www.ruby-forum.com/t/self-in-before-create/53855 "2006-02-15T13:33:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bjarki\_Gudlaugsson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/c89c15/32.png) [@Bjarki\_Gudlaugsson](https://www.ruby-forum.com/u/Bjarki_Gudlaugsson)\
**Post date:** [February 15, 2006, 1:33pm UTC](https://www.ruby-forum.com/t/self-in-before-create/53855/1 "2006-02-15T13:33:05Z")

</div>

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:

---

<div class="post-metadata">

**Author:** ![Bjarki\_Gudlaugsson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/c89c15/32.png) [@Bjarki\_Gudlaugsson](https://www.ruby-forum.com/u/Bjarki_Gudlaugsson)\
**Post date:** [February 15, 2006, 11:05pm UTC](https://www.ruby-forum.com/t/self-in-before-create/53855/2 "2006-02-15T23:05:30Z")

</div>

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
