如何删除单个 HABTM 关联项目而不删除该项目本身?

发布于 2024-07-26 10:45:25 字数 233 浏览 3 评论 0原文

如何删除 HABTM 关联项目而不删除该项目本身?

例如,假设我有 3 个学生一起上科学课。 如何从 StudentsClasses 表中删除 Science 对象而不删除实际的 Science 参考? 我猜 Student.Classes.first.delete 不是一个好主意。

我使用带有拖放功能的 JavaScript 来添加和删除,而不是复选框。 有什么想法吗?

How do you remove a HABTM associated item without deleting the item itself?

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.

I'm using JavaScript with drag-and-drop for adding and removing, not check boxes. Any thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

任谁 2024-08-02 10:45:25

我倾向于使用 has_many :through,但是你尝试过吗?

student.classes.delete(science)

我认为需要目标对象,而不仅仅是 ID,是 HABTM 的限制(因为为了方便起见,连接表被抽象出来)。 如果您使用 has_many :through ,您可以直接对连接表进行操作(因为您获得了模型),这可以让您将此类事情优化为更少的查询。

def leave_class(class_id)
  ClassMembership.delete(:all, :conditions => ["student_id = ? and class_id = ?", self.id, class_id)
end

如果您想要 HABTM 的简单性,您需要使用

student.classes.delete(Class.find 2)

另外,将模型称为“类”是一个非常糟糕的主意。 使用不属于 Ruby 核心的名称!

I tend to use has_many :through, but have you tried

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.

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

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!

难理解 2024-08-02 10:45:25

如果你想删除多个关联的项目,你可以使用 * 并编写:

student.classes.delete(*classes_array)

If you want to delete multiple associated items you can use * and write:

student.classes.delete(*classes_array)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文