Rails,使用 :has_many 删除子项而不删除父项
我
class MyContainer < ActiveRecord::Base
:has_many MyObjects, :dependent => :destroy
end
想删除容器中的所有 MyObjects
而不必删除 MyContainer
。我的模型确实有 :dependent =>; :destroy
,但是我不想删除并重新创建该对象,因为它速度较慢。
像这样的事情是行不通的:
@obj = MyContainer.find_by_id(10)
@obj.my_objects.delete_all
我怎样才能做到这一点?
I have
class MyContainer < ActiveRecord::Base
:has_many MyObjects, :dependent => :destroy
end
I want to delete all the MyObjects
in the container without having to delete the MyContainer
. My model does have :dependent => :destroy
, however I don't want to have to delete and re-create the object because it is slower.
Something like this does not work:
@obj = MyContainer.find_by_id(10)
@obj.my_objects.delete_all
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
delete_all
是一个ActiveRecord: :基类方法。
您应该使用
destroy_all
。像这样的事情:如果您不需要先查找
MyContainer
(或将其用于其他东西),则正确使用delete_all
会更快编辑:对于 Rails 3
delete_all
is anActiveRecord::Base
class method.You should use
destroy_all
. Something like:Using
delete_all
properly would be faster if you don't need to lookup yourMyContainer
first (or use it for other stuff)EDIT: for rails 3