HABTM关联中连接表中的记录自动销毁?
假设我有一个关联,其中用户拥有并属于多个角色。当我销毁用户时,连接表中的记录是否也会自动删除?或者我需要使用 :dependent => :破坏?如果我销毁一个角色怎么办?
class User < ActiveRecord::Base
has_and_belong_to_many :roles # need to use :dependent => :destroy to remove join record?
end
class Role < ActiveRecord::Base
has_and_belong_to_many :users # need to use :dependent => :destroy to remove join record?
end
Let's say I have an association where User has and belongs to many Roles. When I destroy the user, is the record in the join table automatically removed as well? Or do I need to use :dependent => :destroy? What about if I destroy a Role?
class User < ActiveRecord::Base
has_and_belong_to_many :roles # need to use :dependent => :destroy to remove join record?
end
class Role < ActiveRecord::Base
has_and_belong_to_many :users # need to use :dependent => :destroy to remove join record?
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
连接表条目已删除,但角色或用户未删除。您无法将依赖的 destroy 子句添加到 has_and_belongs_to_many,但如果需要,可以将它们添加到连接模型中的关系中。例如,要在删除关联的连接表条目时销毁角色,您可以执行以下操作:
The join table entry is removed but the Role or User is not removed. You can't add a dependent destroy clause to has_and_belongs_to_many, but you can add them to the relations in your join model if you want to. For example to destroy a role when the associated join table entry is removed you would do the following:
已确认 - 当您删除用户或角色时,连接表中具有该用户/角色的所有记录也将被删除
Confirmed - When you delete a user or role, all of the records in the join table with that user / role will also get deleted