如何删除单个 HABTM 关联项目而不删除该项目本身?
如何删除 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我倾向于使用 has_many :through,但是你尝试过吗?
我认为需要目标对象,而不仅仅是 ID,是 HABTM 的限制(因为为了方便起见,连接表被抽象出来)。 如果您使用 has_many :through ,您可以直接对连接表进行操作(因为您获得了模型),这可以让您将此类事情优化为更少的查询。
如果您想要 HABTM 的简单性,您需要使用
另外,将模型称为“类”是一个非常糟糕的主意。 使用不属于 Ruby 核心的名称!
I tend to use has_many :through, but have you tried
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.
If you want the simplicity of HABTM you need to use
Also, calling a model "Class" is a really bad idea. Use a name that isn't part of the core of Ruby!
如果你想删除多个关联的项目,你可以使用
*
并编写:If you want to delete multiple associated items you can use
*
and write: