首页 > 解决方案 > 如何自动销毁accepted_nested_attributes_for的关联

问题描述

我有User多个Posts

class User
  has_many :posts
  accepts_nested_attributes_for :posts, allow_destroy: true
end

class Post
  belongs_to :user
end

在控制器中,我将通过更新

@user.update({ posts_attributes: [{uuid:'blah1'},{uuid:'blah2'}] })

posts我希望它可以在每次更新中自动销毁不存在的东西。

@user.update({ posts_attributes: [{uuid:'blah1'},{uuid:'blah2'}] }) # create blah1, create blah2
@user.update({ posts_attributes: [{uuid:'blah2'},{uuid:'blah3'}] }) # delete blah1, create blah3

我怎样才能做到这一点?

更新:

我知道这可以通过

@user.update({ posts_attributes: [{uuid:'blah1',:_destroy:true},{uuid:'blah2'},{uuid:'blah3'}] })

但从我的角度来看,这并不体面。它可以是内部模型而不是外部模型吗?

更新:

我找到了这个链接,但它看起来很复杂。

标签: ruby-on-rails

解决方案


推荐阅读