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

时间:2015-03-23 12:31:16

标签: ruby-on-rails observers

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

无法弄明白为什么,任何人都可以提供一些帮助吗?非常感谢。

2 个答案:

答案 0 :(得分:0)

在您的情况下,您需要确保使用密钥address_attributes和正确的id传入参数。如果您不包含id,则会创建一条记录。这就是为after_create而不是after_update而开火的原因。

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

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

以下是相关文档:ActiveRecord::NestedAttributes::ClassMethods

  

现在,您可以通过成员的属性哈希在关联的帖子上设置或更新属性:包括键:posts_attributes,其中包含一系列post属性的哈希值作为值。   对于没有id密钥的每个哈希,新记录将被实例化[...]

答案 1 :(得分:0)

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

after_commit :add_count_in_profile, on: :create


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