Ruby-on-rails Rails 从父级中删除子级关联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12023854/
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
Rails Remove child association from parent
提问by Wes Foster
I have this (Contract and Accessory are associated with has_and_belongs_to_many):
我有这个(合同和附件与 has_and_belongs_to_many 相关联):
# Get the contract and specific accessory based on params
@contract = Contract.find(params[:id])
@accessory = @contract.accessories.find(params[:accessory_id])
Now, I'm wanting to remove that specific accessory from @contract. I don't want to delete the record from the DB, but simply want to remove the association between the two.
现在,我想从@contract 中删除该特定附件。我不想从数据库中删除记录,而只想删除两者之间的关联。
What's the railsy way of doing this?
这样做的愚蠢方法是什么?
Thanks!
谢谢!
回答by Chris Salzberg
How about this:
这个怎么样:
@contract.accessories.delete(@accessory)
See also: How do I remove a single HABTM associated item without deleting the item itself?

