Techioz Blog

accepts_nested_attributes_for および after_remove

概要

こんなモデルあるんですね

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

ビューに新しいコメントを追加すると、そのオブジェクトが post.soiled_associations 属性に追加されます (ところで、soiled_associations は、Rails の Dirty クラスに似た処理を行うカスタム メソッドに名前を付ける試みですが、アソシエーション用です)。

ただし、ビュー内のコメントを削除しても、post.soiled_associations 属性には何も追加されません。

私の何が間違っているのでしょうか? accepts_nested_attributes_for がどのように機能するか (おそらくこれらのコールバックをバイパスする) に問題があるのではないかと思いますが、誰かがこれについて光を当てることができますか?

解決策

自分が何をしているのかを示していないので、何が間違っているのかを伝えることはできません。しかし、それを行う方法はいくつかしかありません。

>> 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>]