【问题标题】:Observer and callback not triggered for accepts_nested_attributes_for未为 accept_nested_attributes_for 触发观察者和回调
【发布时间】:2012-01-26 17:12:04
【问题描述】:

我有一个模型主题和帖子。主题 has_many :posts.

在主题模型中,我也接受了_nested_attributes_for:posts,

似乎在使用 Post 的某些参数更新 Topic 时,不会触发 Post 模型的观察者和回调。是错误还是功能?

【问题讨论】:

  • 您是否在config/application.rb 中启用了您的观察者?你必须重新启动服务器。
  • 当然,我之前使用过那个观察者,用于定期模型更新,而不是通过嵌套属性
  • 你也应该发布你的观察者代码。
  • 您确定在 Topic 模型的 attr_accessible 中有 :posts_attributes 吗?
  • 尝试启动 rails 控制台并保存或更新帖子。观察者跑了吗?

标签: ruby-on-rails callback observer-pattern nested-attributes


【解决方案1】:

不确定您所说的“使用 Post 的某些参数更新 Topic 时”是什么意思,但 Post 回调只会在您更新 post 对象时运行。

即这将触发回调:

@post.update_attributes(:topics_attributes => [...])

...但这不会:

@topic.update_attributes(:post_id => 123, ...)

如果您想在主题更新时触发Post after_update 回调,您可以这样做:

# topic.rb
after_update :touch_post
private
def touch_post
  post.touch
end

观察者代码的行为类似于回调。

【讨论】:

    【解决方案2】:

    当您在嵌套资源上运行 update_attributes 方法时,仅在 如果它已更改并且如果它通过验证,则保存资源:如果没有,则不保存资源并且 after_update 没有被触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      相关资源
      最近更新 更多