如何删除不删除项本身的单一HABTM相关的项目? [英] How do I remove a single HABTM associated item without deleting the item itself?
问题描述
你如何删除HABTM相关的项目,而不删除项目本身?
How do you remove a HABTM associated item without deleting the item itself?
举例来说,假设我有3个学生是在科学类在一起。如何删除而不删除实际的科学参考科学从StudentsClasses表对象?我猜 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:通过,但你试过
I tend to use has_many :through, but have you tried
student.classes.delete(science)
我觉得需要有目标对象,而不仅仅是ID,是HABTM的限制(因为连接表抽离为了您的方便)。如果您使用的has_many:通过您可以在连接表直接操作(因为你得到一个模型),并且让您优化这样的事情到较少的查询
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)
此外,调用模型类是一个非常糟糕的主意。使用一个名称,是不是红宝石的核心的一部分!
Also, calling a model "Class" is a really bad idea. Use a name that isn't part of the core of Ruby!
这篇关于如何删除不删除项本身的单一HABTM相关的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!