仅在创建对象时调用after_update

时间:2014-09-02 18:57:32

标签: ruby-on-rails activerecord rails-activerecord

我有两个类和一个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

当用户更新时,我创建一个foo并保存它。但是当我这样做时,正在调用after_update中的Foo回调,据我所知,只有在未创建记录更新时才调用该回调。我做错了什么?

1 个答案:

答案 0 :(得分:5)

正在调用

Foo#after_update,因为您在创建它之后在foo上调用save。所以你创建foo然后更新它。移除对self.foo.save

的调用
before_update do |user|
  self.foo = Foo.create  # this creates foo
  self.foo.save          # this updates foo
end
相关问题