Rails 3:HABTM、destroy 和 before_destroy 回调
如果我正确阅读了 Rails 指南,则返回 false 的 before_destroy 回调将通过发出回滚命令来阻止对象被销毁。
然而,虽然对象本身没有被删除,但我发现该对象上的 HABTM 关系中的所有对象都被删除了。我怎样才能阻止这种情况发生?
下面是适当的代码块:
class UserGroup < ActiveRecord::Base
# Associations
has_and_belongs_to_many :users, :join_table => "user_group_membership"
attr_protected :is_default
# Callbacks
before_destroy :destroy_associations
def destroy_associations
if self.is_default?
errors.add(:base,"You can't delete the default")
return false
end
self.users.clear
end
end
现在,当我对“is_default”组调用 destroy 时,我会收到添加到基础中的正确错误消息,UserGroup 对象不会被销毁,但 :users 集合中的每个关联都会被清除。
我知道代码“self.users.clear”永远不会到达 - 那么为什么我会丢失我的 HABTM 集合?
如果有帮助的话,我正在使用 JRuby 1.9 和 mssql 数据库。
If I have read the rails guides correctly, a before_destroy callback that returns false will stop the object being destroyed by issuing a rollback command.
However, while the object itself is not being removed I'm finding that all objects in a HABTM relationship on that object are. How can I stop this from happening?
Here's the appropriate code block:
class UserGroup < ActiveRecord::Base
# Associations
has_and_belongs_to_many :users, :join_table => "user_group_membership"
attr_protected :is_default
# Callbacks
before_destroy :destroy_associations
def destroy_associations
if self.is_default?
errors.add(:base,"You can't delete the default")
return false
end
self.users.clear
end
end
Now when I call destroy on a "is_default" group, I get the correct error message added to the base, the UserGroup object is NOT destroyed but every association in the :users collection is cleared.
I know that the code "self.users.clear" is never reached - so why am I losing my HABTM collection?
If it helps, I am using JRuby 1.9 with an mssql database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论