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

后端 未结 2 1534
灰色年华
灰色年华 2020-12-28 12:39

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

相关标签:
2条回答
  • 2020-12-28 12:59

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

    student.classes.delete(*classes_array)
    
    0 讨论(0)
  • 2020-12-28 13:00

    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!

    0 讨论(0)
提交回复
热议问题