嵌套属性更新在观察者中触发错误回调

nested attributes update triggers wrong callback in observer

app/model中的两个类:

class Job
  accepts_nested_attributes_for :address
end

class Address
end

然后在 jobs_controllerupdate 方法中,我执行 @job.update(job_params),地址参数包含在表单提交的 job_params 中。

地址可以正确更新,但是地址观察器的行为不正常。相反 after_updated 被调用,它实际上在地址更新时触发 after_create

address_observer.rb

# cannot be triggered when address gets updated
def after_update(address)
end

# can be triggered when address gets updated
def after_create(address)
end

无法弄清楚为什么,任何人都可以提供一些帮助吗?提前致谢。

在您的情况下,您需要确保使用键 address_attributes 和正确的 id 传入参数。如果不包括 id,将创建一条记录。这就是 after_create 而不是 after_update 的原因。

这是一个例子(假设 has_one 关系:)

{ job: { address_attributes: { id: 1, foo: 'bar' } } }

这里是相关文档:ActiveRecord::NestedAttributes::ClassMethods

You can now set or update attributes on the associated posts through an attribute hash for a member: include the key :posts_attributes with an array of hashes of post attributes as a value. For each hash that does not have an id key a new record will be instantiated [...]

而不是观察者..在模型中使用回调...

after_commit :add_count_in_profile, on: :create


def add_count_in_profile
  Rails.logger.info  "---------updating images count in the profile for #
end