如果更新参数中不存在关联记录,则自动删除

时间:2019-04-22 16:32:02

标签: ruby-on-rails activerecord associations

我们将Rails 5.2.2.1用作具有Vue前端的API。

一个Post has_many :tagsPost也是accepts_nested_attributes_for :tags, allow_destroy: true

创建帖子时,您可以同时创建标签,效果很好。但是,在编辑标签时,我遇到了一个问题,即更新有效负载中不存在的标签没有从数据库中删除。这是我期望的示例:

# A Post has currently tags with ID 1, 2, and 3.
# This (pseudo) update payload is sent
{
  tags_attributes: [
    {
      id: 1,
      name: 'Tech'
    },
    {
      id: 3,
      name: 'Sports'
    },
    {
      id: nil,
      name: 'Science'
    }
  ]
}

# The post's tag with an ID of 2 is not present in the update payload, so it should be automatically removed
# Since we're also passing up a new tag without an ID, this tag should be created

我有一个涉及_destroy: '1'的解决方案,但是最好根据标签在更新有效载荷中的存在来自动将其标记为销毁。

0 个答案:

没有答案
相关问题