从 has_many 中删除对象但不删除 Rails 中的原始记录? [英] Remove object from has_many but don't delete the original record in Rails?
本文介绍了从 has_many 中删除对象但不删除 Rails 中的原始记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
Post.paragraphs << new_paragraph
并且我需要通过 id = 3 删除段落,因此以下内容完全删除了记录:
And I need to remove paragraph by id = 3, so the following deletes the record completely:
Post.paragraphs.find(paragraph_id).destroy
# or
Post.paragraphs.find(paragraph_id).delete
我只需要从 has_many 关联中删除一个段落.我尝试使用 delete
和 destroy
.这两种方法都从关联的表中完全删除记录.我怎样才能从容器"中删除它们?
I just need to remove a paragraph from has_many association. I tried to use delete
and destroy
. Both methods completely delete records from the associated tables. How can I just remove them from the "container"?
推荐答案
你不应该在 Paragraph
对象上使用 delete
方法,而是使用paragraphs
关系,像这样:
You should not use the delete
method on the Paragraph
object, but instead use the delete method of paragraphs
relation, like this:
post.paragraphs.delete(Paragraph.find(paragraph_id))
这篇关于从 has_many 中删除对象但不删除 Rails 中的原始记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文