Reputation: 941
I have a model like so
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
When I add a new comment
in the view it adds the object to my post.soiled_associations
attribute (BTW soiled_associations
is my attempt to name a custom method that does something similar to Rails's Dirty
class, but for associations).
However, when I delete a comment in my view nothing gets added to the post.soiled_associations
attribute.
What am I doing wrong? I suspect it is in something about how accepts_nested_attributes_for
works (perhaps bypassing these callbacks) but can anybody shed some light on this?
Upvotes: 0
Views: 49
Reputation: 29821
Can't tell you what you are doing wrong since you haven't shown what you're doing. But there are only a few ways to do it:
>> 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>]
Upvotes: 1