accepts_nested_attributes_for 和 after_remove

问题描述 投票:0回答:1

我有一个这样的模型

class Post < ApplicationRecord

  has_many :comments,
            after_add: :soil,
            after_remove: :soil,
            dependent: :destroy

  attr_accessor :soiled_associations

  accepts_nested_attributes_for :comments, allow_destroy: true

  def soil(record)
    self.soiled_associations = [record]
  end
end

当我在视图中添加新的

comment
时,它会将对象添加到我的
post.soiled_associations
属性中(顺便说一句,
soiled_associations
是我尝试命名一个自定义方法,该方法执行与 Rails 的
Dirty
类类似的操作,但用于关联) .

但是,当我删除视图中的评论时,

post.soiled_associations
属性中不会添加任何内容。

我做错了什么?我怀疑这与

accepts_nested_attributes_for
的工作原理有关(可能绕过这些回调),但有人能解释一下吗?

ruby-on-rails ruby callback accepts-nested-attributes-for
1个回答
0
投票

无法告诉你你做错了什么,因为你还没有表明你在做什么。但只有几种方法可以做到:

>> Post.new(comments_attributes: [{}]).soiled_associations
=> [#<Comment:0x00007f01e99a30c0 id: nil, post_id: nil>]

>> Post.create(comments_attributes: [{}]).soiled_associations
=> [#<Comment:0x00007f01e9a08fd8 id: 3, post_id: 2>]

>> post = Post.last
>> post.comments.destroy_all
>> post.soiled_associations
=> [#<Comment:0x00007f01e99867e0 id: 3, post_id: 2>]

>> Post.create(comments_attributes: [{}])
>> post = Post.last
>> post.update(comments_attributes: [{id: 4, _destroy: true}])
>> post.soiled_associations
=> [#<Comment:0x00007f01e99a5500 id: 4, post_id: 3>]
© www.soinside.com 2019 - 2024. All rights reserved.