我们将Rails 5.2.2.1用作具有Vue前端的API。
一个Post
has_many :tags
。 Post
也是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'
的解决方案,但是最好根据标签在更新有效载荷中的存在来自动将其标记为销毁。