Forum: Ruby on Rails self in before_create

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Bjarki Gudlaugsson (Guest)
on 2006-02-15 14:33
(Received via mailing list)
Hi, I am having a small problem concernig how to access local variables
before_create. I am not sure how to really form this question but here

I am wondering why this works

  def before_create
    self.last_logged_in =
    self.created =

but this doesn't

  def before_create
    @last_logged_in =
    @created =

The latter fails with the following error:

Mysql::Error: #23000Column 'last_logged_in' cannot be null:
Matthew P. (Guest)
on 2006-02-16 00:05
(Received via mailing list)
On Tue, Feb 14, 2006 at 06:29:16PM +0000, Bjarki Gudlaugsson wrote:
> but this doesn't
>   def before_create
>     @last_logged_in =
>     @created =
>   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 --
actually values in the @attributes (from memory) instance variable.  So
you'd need to do

def before_create
  @attributes['last_logged_in'] =
  @attributes['created'] =

But, of course, that's a damn sight longer than self.<whatever>, so
with that.

On another optimisation point, if you create a field in your database
'created_at', AR will automatically fill that field out with at
object creation time, which will save you a couple of lines of code here

- Matt
This topic is locked and can not be replied to.