Forum: Ruby on Rails self in before_create

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.
Af1a7e2fc9e56e1da6bda562e3ba4ab3?d=identicon&s=25 Bjarki Gudlaugsson (Guest)
on 2006-02-15 13:33
(Received via mailing list)
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:
55428cbf149e35dd4b65f1d019d04139?d=identicon&s=25 Matthew Palmer (Guest)
on 2006-02-15 23: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 = 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.<whatever>, 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
This topic is locked and can not be replied to.