How to determine if an object has just been created


#1

Is there a built-in way to determine if a model object has just been
created (ie. this object was the one that was originally persisted)? I
can’t see it anywhere in the AR code, but thought I’d check. I want
something like:

p = Person.create
p.original_instance? # true

Is this built-in or should I just patch AR?

-Jonathan.


#2

Jonathan V. wrote:

Is there a built-in way to determine if a model object has just been
created (ie. this object was the one that was originally persisted)? I
can’t see it anywhere in the AR code, but thought I’d check. I want
something like:

p = Person.create
p.original_instance? # true

Is this built-in or should I just patch AR?
Not sure quite what you’re after, but does p.new_record? do the trick?


#3

On 5/19/06, Jonathan V. removed_email_address@domain.invalid wrote:

-Jonathan.


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

I don’t think there’s a built-in way to do that…but it seems like
it’d be pretty simple.

def original_instance?
!new_record? && created_at == updated_at
end

and just add created_at and updated_at fields to your model.

Pat


#4

I don’t think there’s a built-in way to do that…but it seems like
it’d be pretty simple.

From documentation:

new_record?
Returns true if this object hasn’t been saved yet â?? that is, a record
for the object doesn’t exist yet.

Regards,
Rimantas


#5

On 5/19/06, Rimantas L. removed_email_address@domain.invalid wrote:

I don’t think there’s a built-in way to do that…but it seems like
it’d be pretty simple.

From documentation:

new_record?
Returns true if this object hasn’t been saved yet ? that is, a record
for the object doesn’t exist yet.

From the OP:
“this object was the one that was originally persisted”

new_record? tells you if the object hasn’t been saved. OP is asking
how to tell if the record is the original one. My interpretation is
basically that the object hasn’t been modified at all. The easiest
way to do that (though perhaps not fool-proof) is to compare the
updated_at and created_at fields. In fact, I used new_record? in my
code.

Another possibility is acts_as_versioned, which may be more air-tight
than my solution (though I don’t know if there are any problems with
it, I just came up with it).

Pat


#6

The reason for doing this is to be able to send emails when certain
models are created and/or changed. I realised just after I made the
post that I should use AR callbacks (after_create and after_update) on
the models, and possibly an observer.

Thanks, -Jonathan.