Ruby-on-rails 如何在不删除项目本身的情况下删除单个 HABTM 关联项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1089892/
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
How do I remove a single HABTM associated item without deleting the item itself?
提问by humble_coder
How do you remove a HABTM associated item without deleting the item itself?
如何在不删除项目本身的情况下删除 HABTM 关联项目?
For example, say I have 3 Students that are in a Science class together. How do I remove the Science objects from the StudentsClasses table without deleting the actual Science reference? I'm guessing that Student.Classes.first.deleteisn't a good idea.
例如,假设我有 3 个学生一起上科学课。如何从 StudentsClasses 表中删除 Science 对象而不删除实际的 Science 引用?我猜这 Student.Classes.first.delete不是一个好主意。
I'm using JavaScript with drag-and-drop for adding and removing, not check boxes. Any thoughts?
我使用带有拖放功能的 JavaScript 来添加和删除,而不是复选框。有什么想法吗?
回答by Michael Sofaer
I tend to use has_many :through, but have you tried
我倾向于使用 has_many :through,但你有没有尝试过
student.classes.delete(science)
I think needing to have the target object, not just the ID, is a limitation of HABTM (since the join table is abstracted away for your convenience). If you use has_many :through you can operate directly on the join table (since you get a Model) and that lets you optimize this sort of thing into fewer queries.
我认为需要目标对象,而不仅仅是 ID,是 HABTM 的一个限制(因为为了您的方便,连接表被抽象掉了)。如果你使用 has_many :through 你可以直接对连接表进行操作(因为你得到了一个模型),这样你就可以将这类事情优化为更少的查询。
def leave_class(class_id)
ClassMembership.delete(:all, :conditions => ["student_id = ? and class_id = ?", self.id, class_id)
end
If you want the simplicity of HABTM you need to use
如果您想要 HABTM 的简单性,您需要使用
student.classes.delete(Class.find 2)
Also, calling a model "Class" is a really bad idea. Use a name that isn't part of the core of Ruby!
此外,将模型称为“类”是一个非常糟糕的主意。使用不属于 Ruby 核心的名称!
回答by GEkk
If you want to delete multiple associated items you can use *and write:
如果要删除多个关联项目,可以使用*并编写:
student.classes.delete(*classes_array)

