How to determine if a record is just created or updated in after_save
Yet another option, for those who do have an updated_at
timestamp:
if created_at == updated_at
# it's a newly created record
end
No rails magic here that I know of, you'll have to do it yourself. You could clean this up using a virtual attribute...
In your model class:
def before_save
@was_a_new_record = new_record?
return true
end
def after_save
if @was_a_new_record
...
end
end
I was looking to use this for an after_save
callback.
A simpler solution is to use id_changed?
(since it won't change on update
) or even created_at_changed?
if timestamp columns are present.
Update: As @mitsy points out, if this check is needed outside of callbacks then use id_previously_changed?
. See docs.