【问题标题】:nested attributes update triggers wrong callback in observer嵌套属性更新在观察者中触发错误回调
【发布时间】:2015-05-26 10:40:26
【问题描述】:

应用/模型中的两个类:

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

不知道为什么,有人可以提供一些帮助吗?提前非常感谢。

【问题讨论】:

    标签: ruby-on-rails observers


    【解决方案1】:

    在您的情况下,您需要确保使用密钥address_attributes 和正确的id 传入参数。如果您不包括id,则会创建一条记录。这就是为什么after_create 被触发而不是after_update

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

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

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

    您现在可以通过成员的属性散列设置或更新关联帖子的属性:将键 :posts_attributes 与帖子属性的散列数组作为值包含在内。 对于每个没有 id 键的哈希,将实例化一个新记录 [...]

    【讨论】:

    • 非常感谢!我只需要在控制器参数要求中通过许可id
    • 我也没有意识到它每次都会创建一条新记录,因为 db 中的地址数不会改变。我刚刚仔细阅读了控制台日志,发现rails实际上删除了旧地址并使用新的id创建了一个新地址。
    • @Shane:这很有趣。我不知道这种行为,但会警告我的同事。
    【解决方案2】:

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

    after_commit :add_count_in_profile, on: :create
    
    
    def add_count_in_profile
      Rails.logger.info  "---------updating images count in the profile for #
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2017-06-15
      • 2023-01-24
      • 2012-11-17
      • 2018-03-11
      • 2023-04-08
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多