11

假设我有一个关联,其中用户拥有并属于许多角色。当我销毁用户时,连接表中的记录是否也会自动删除?还是我需要使用 :dependent => :destroy?如果我销毁一个角色怎么办?

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
4

2 回答 2

10

连接表条目被删除,但角色或用户没有被删除。您不能在 has_and_belongs_to_many 中添加从属破坏子句,但如果您愿意,可以将它们添加到连接模型中的关系中。例如,要在删除关联的连接表条目时销毁角色,您可以执行以下操作:

class RolesUser < ActiveRecord::Base
  belongs_to :role, :dependent => :destroy
  belongs_to :user
end
于 2011-02-16T17:21:52.910 回答
0

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

于 2016-04-04T00:30:47.303 回答