关联的“保存前”回调

2024-01-11

保存父对象时如何调用关联上的“before_save”回调?例如:

class Company < ActiveRecord::Base
  belongs_to :user

  before_save Proc.new { ... } # Not called.
end

class User < ActiveRecord::Base
  has_one :company

  before_save Proc.new { ... } # Gets called.
end

params = { 
  :user => { 
    :name => "Kevin Sylvestre", 
    :company_attributes => { :city => "Waterloo", :region => "Ontario" } 
  }
}

@user = User.new(params[:user])
@user.save

是否对用户调用“before_save”,但不对公司调用“before_save”。谢谢。


你可以使用这个patch https://rails.lighthouseapp.com/projects/8994/tickets/4392-add-touch-option-to-has_many-associations它将“touch”功能添加到 has_one 关联中,或者只是在 User 模型中定义另一个 after_save 回调,并在那里显式“touch”Company 实例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关联的“保存前”回调 的相关文章

随机推荐