如何在不删除项目本身的情况下删除单个 HABTM 关联项目?

编程入门 行业动态 更新时间:2024-10-27 20:29:44
本文介绍了如何在不删除项目本身的情况下删除单个 HABTM 关联项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在不删除项目本身的情况下删除 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 关联项目?

本文发布于:2023-05-31 12:01:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/391367.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   情况下   如何在   HABTM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!