After_update is called when the object is only created

I have two classes and an association belongs_to

:

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 the user is updated, I create foo and save it. But when I do this, a callback is called after_update

in Foo

, which as far as I know is only called when the record is not updated. What am I doing wrong?

+3


source to share


1 answer


Foo#after_update

called because you are calling save

on foo after you create it. So you create foo

and then update it after. Delete the callself.foo.save



before_update do |user|
  self.foo = Foo.create  # this creates foo
  self.foo.save          # this updates foo
end

      

+5


source







All Articles