本文介绍了“保存前"关联回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存父对象时如何调用关联的before_save"回调?例如:

How do you call the "before_save" callbacks on an association when saving the parent object? For example:

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",而不是对公司调用.谢谢.

Does calls "before_save" on the user, but not on the company. Thanks.

推荐答案

您可以使用这个 patch 将touch"功能添加到 has_one 关联,或者只是在 User 模型中定义另一个 after_save 回调并在那里显式touch"公司实例.

You can either use this patch that adds the "touch" functionality to the has_one association or just define another after_save callback in the User model and "touch" the Company instance explicitly there.

这篇关于“保存前"关联回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:03