HABTM关联中连接表中的记录自动销毁?

发布于 2024-10-17 20:20:33 字数 393 浏览 1 评论 0原文

假设我有一个关联,其中用户拥有并属于多个角色。当我销毁用户时,连接表中的记录是否也会自动删除?或者我需要使用 :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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

段念尘 2024-10-24 20:20:33

连接表条目已删除,但角色或用户未删除。您无法将依赖的 destroy 子句添加到 has_and_belongs_to_many,但如果需要,可以将它们添加到连接模型中的关系中。例如,要在删除关联的连接表条目时销毁角色,您可以执行以下操作:

class RolesUser < ActiveRecord::Base
  belongs_to :role, :dependent => :destroy
  belongs_to :user
end

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:

class RolesUser < ActiveRecord::Base
  belongs_to :role, :dependent => :destroy
  belongs_to :user
end
怪异←思 2024-10-24 20:20:33

已确认 - 当您删除用户或角色时,连接表中具有该用户/角色的所有记录也将被删除

Confirmed - When you delete a user or role, all of the records in the join table with that user / role will also get deleted

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文