Ruby-on-rails 从 has_many 中删除对象但不删除 Rails 中的原始记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25660419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:53:52  来源:igfitidea点击:

Remove object from has_many but don't delete the original record in Rails?

ruby-on-railsactiverecordcollectionsremove-if

提问by valk

I have this:

我有这个:

Post.paragraphs << new_paragraph

And I need to remove paragraph by id = 3, so the following deletes the record completely:

我需要按 id = 3 删除段落,因此以下内容将完全删除记录:

Post.paragraphs.find(paragraph_id).destroy
# or
Post.paragraphs.find(paragraph_id).delete

I just need to remove a paragraph from has_many association. I tried to use deleteand destroy. Both methods completely delete records from the associated tables. How can I just remove them from the "container"?

我只需要从 has_many 关联中删除一个段落。我尝试使用deletedestroy。这两种方法都从关联的表中完全删除记录。我怎样才能从“容器”中删除它们?

回答by Baldrick

You should not use the deletemethod on the Paragraphobject, but instead use the delete method of paragraphsrelation, like this:

您不应该deleteParagraph对象上使用该方法,而应使用paragraphs关系的删除方法,如下所示:

post.paragraphs.delete(Paragraph.find(paragraph_id))