【问题标题】:How to process new children in before_update callback for activerecord nested attributes如何在 before_update 回调中处理 activerecord 嵌套属性的新子级
【发布时间】:2010-01-07 14:49:43
【问题描述】:

我有一个模型对象(假设是 Parent),它与另一个模型对象(Child)上的 has_many 关联。

class Parent < ActiveRecord::Base
    has_many :children
    accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
    belongs_to :parent
end

在父级上,我想在 before_update 回调中添加代码,以根据其子级设置计算属性。

我遇到的问题是,当我使用 Parent.update(id, atts) 方法为新子代添加 atts 时,在 before_update 期间添加到 atts 集合中的那些不可用(self.children 返回旧收藏)。

有没有办法在不弄乱accept_nested_attributes_for 的情况下检索新的?

【问题讨论】:

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


    【解决方案1】:

    您所描述的内容适用于 Rails 2.3.2。我认为您可能没有正确分配给父母的孩子。更新后孩子有更新吗?

    accepts_nested_attributes_for,如您的问题中所用,在父级上创建一个 child_attributes 编写器。我感觉您正在尝试更新 :children 而不是 :children_attributes。

    这可以使用您描述的模型和以下 before_update 回调:

    before_update :list_childrens_names
    def list_childrens_names
      children.each{|child| puts child.name}
    end
    

    控制台中的这些命令:

    Parent.create # => Parent(id => 1)
    Parent.update(1, :childrens_attributes => 
      [{:name => "Jimmy"}, {:name => "Julie"}]) 
    

    产生这个输出:

    Jimmy
    Julie
    

    【讨论】:

    • 是的,刚刚测试过,您的版本可以正常工作。问题是我依赖于儿童计数,它返回旧计数。 children.count 和 children.all.size 都返回 0,而使用 each 的迭代实际上打印了元素。关于获得实际计数的任何想法?
    • 好吧,在请求大小之前迭代连接有效,我会采用这种方法。
    • 这很奇怪。 children.size 有效,但 children.all.size 或 children.count 无效。谨防依赖计数。如果您要删除项目,则计数将关闭,因为它仍会计算那些标记为删除的项目。你需要做类似 children.reject(&:marked_for_deletion).count
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多