问题描述
如何在不删除项目本身的情况下删除 HABTM 关联项目?
How do you remove a HABTM associated item without deleting the item itself?
例如,假设我有 3 个学生一起上科学课.如何从 StudentsClasses 表中删除 Science 对象而不删除实际的 Science 引用?我猜 Student.Classes.first.delete
不是一个好主意.
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.delete
isn't a good idea.
我使用 JavaScript 通过拖放进行添加和删除,而不是复选框.有什么想法吗?
I'm using JavaScript with drag-and-drop for adding and removing, not check boxes. Any thoughts?
推荐答案
我倾向于使用 has_many :through,但是你试过了吗
I tend to use has_many :through, but have you tried
student.classes.delete(science)
我认为需要目标对象,而不仅仅是 ID,是 HABTM 的一个限制(因为为了您的方便,连接表被抽象掉了).如果你使用 has_many :through 你可以直接对连接表进行操作(因为你得到了一个模型),这样你就可以将这类事情优化为更少的查询.
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.
def leave_class(class_id)
ClassMembership.delete(:all, :conditions => ["student_id = ? and class_id = ?", self.id, class_id)
end
如果你想要 HABTM 的简单性,你需要使用
If you want the simplicity of HABTM you need to use
student.classes.delete(Class.find 2)
此外,将模型称为类"是一个非常糟糕的主意.使用不属于 Ruby 核心的名称!
Also, calling a model "Class" is a really bad idea. Use a name that isn't part of the core of Ruby!
这篇关于如何在不删除项目本身的情况下删除单个 HABTM 关联项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!