Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I remove a single HABTM associated item without deleting the item itself?

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?

question from:https://stackoverflow.com/questions/1089892/how-do-i-remove-a-single-habtm-associated-item-without-deleting-the-item-itself

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...