Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a record is just created or updated in after_save

The #new_record? function determines if a record has been saved. But it is always false in the after_save hook. Is there a way to determine whether the record is a newly created record or an old one from update?

I'm hoping not to use another callback such as before_create to set a flag in the model or require another query into the db.

Any advice is appreciated.

Edit: Need to determine it in after_save hook, and for my particular use case, there is no updated_at or updated_on timestamp

like image 587
Aaron Qian Avatar asked Feb 11 '11 23:02

Aaron Qian


3 Answers

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.

like image 185
Zubin Avatar answered Nov 12 '22 07:11

Zubin


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
like image 32
Jeff Paquette Avatar answered Nov 12 '22 07:11

Jeff Paquette


Yet another option, for those who do have an updated_at timestamp:

if created_at == updated_at
  # it's a newly created record
end
like image 30
colllin Avatar answered Nov 12 '22 07:11

colllin