【问题标题】:Does ActiveRecord have a way of reporting that a nested attribute model has been destroyed?ActiveRecord 是否有报告嵌套属性模型已被破坏的方法?
【发布时间】:2012-08-29 00:20:02
【问题描述】:

我正在使用 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 定义的父模型的实例变量中。

【问题讨论】:

    标签: ruby-on-rails nested-attributes


    【解决方案1】:

    :after_destroy followup_tasks 回调广告到详细模型(子)

    def followup_tasks
      #do other stuff
    end
    

    【讨论】:

    • 是的,我想我必须做这样的事情。现在我已经尝试过了,但我看不到如何从这个回调中将某些东西传递给父模型。我尝试在父模型上设置一个实例变量,但在删除子模型后,它没有出现在我的控制器中的模型实例中。嗯嗯。
    • 我在stackoverflow.com/questions/12171216问了另一个问题
    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2013-12-01
    • 2015-04-28
    • 1970-01-01
    相关资源
    最近更新 更多