How to determine if a record was created or updated in after_save callback (Ruby on Rails)

sometimes in after_save callback it is needed to determine if a record was created or updated without the use of after_create callback.

Rails has no direct way for doing this.

The solution can be as follows:

[codesyntax lang=”rails”]

def before_save
  @was_a_new_record = new_record?
  return true
end

def after_save
  if @was_a_new_record
    ...
  end
end

[/codesyntax]

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>