0

我正在使用该previous_changes方法来确定对我的 ActiveRecord 模型的更改以通过 JSON 传回,并且想知道是否有类似的东西告诉我嵌套属性已被破坏。

例如,如果Parent has_many ChildrenParent accepts_nested_attributes_for :children, allow_destroy: true希望能够执行以下操作。

> p = Parent.last
> p.children.length
=> 3
> p.update_attributes {"name"=>"Daddy","children_attributes"=>{"0"=>{"__destroy"=>"1","id"=>"12"}}}
=> true
>p.previous_changes
=> {"name"=>["", "Daddy"], "updated_at"=>[Mon, 27 Aug 2012 22:34:34 EST +10:00, Wed, 29 Aug 2012 10:13:33 EST +10:00]}
>p.destroyed_attributes #Not a real method!!!
=> {"children_attributes"=>{"0"=>{"id"=>"12"}}}

这是我想要的最后一个命令。我可以制定自己的解决方案来获取这些信息,但我希望 Rails 中已经有一些东西可以为我做到这一点。

编辑:

似乎没有内置的方法可以做到这一点,但我确实想出了一个解决方案。在我的父模型中,我定义了一个 before_save 和 after_save 回调。在 before_save 中,我保存了一个包含所有子 ID 的数组。在 after_save 中,我减去了一个包含所有子 ID 的数组。数组中剩余的任何 id 都已被删除!我将数组存储在使用 attr_accessor 定义的父模型的实例变量中。

4

1 回答 1

1

添加对详细模型(子)的:after_destroy followup_tasks回调

def followup_tasks
  #do other stuff
end
于 2012-08-29T00:40:08.053 回答