Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after_update is called when the object is only created

I have two classes and a belongs_to association:

class User < ActiveRecord::Base
  belongs_to :foo

  before_update do |user|
    self.foo = Foo.create
    self.foo.save
  end
end

class Foo < ActiveRecord::Base
  after_update do |foo|
    puts "after update is called"
  end
end

When a user is updated, i create a foo and save it. But when i do that the after_update callback in the Foo is being called, which as far as i know is only called when the record is updated not created. What am i doing wrong?

like image 540
lunr Avatar asked Feb 02 '26 14:02

lunr


1 Answers

Foo#after_update is being called because you are calling save on foo after creating it. So you are creating foo and then updating it after. Remove the call to self.foo.save

before_update do |user|
  self.foo = Foo.create  # this creates foo
  self.foo.save          # this updates foo
end
like image 188
infused Avatar answered Feb 05 '26 03:02

infused



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!