Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback - after_save but NOT create

How can you separate callbacks so that after_create runs one set of code, but !after_create, so to speak, runs another?

like image 802
sscirrus Avatar asked Apr 23 '11 20:04

sscirrus


3 Answers

after_create After new object created

after_update After existing object updated

after_save Both creation and update

like image 149
Mirror318 Avatar answered Oct 11 '22 12:10

Mirror318


after_create callback for new object, after_update for persisted one.

like image 24
Voldy Avatar answered Oct 11 '22 14:10

Voldy


You can have multiple callbacks which only execute based on conditions

model.rb

after_create :only_do_if_this
after_create :only_do_if_that

def only_do_if_this
  if do_this?
    # code...
  end
end

def only_do_if_that
  if do_that?
    # code...
  end
end

You can also add the condition to the callback itself

after_create :only_do_if_this, :if => proc { |m| m.do_this? }
after_create :only_do_if_that, :if => proc { |m| m.do_that? }

def only_do_if_this
  # code ...
end

def only_do_if_that
  # code...
end
like image 37
nowk Avatar answered Oct 11 '22 14:10

nowk