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

时间:2011-02-16 17:04:22

标签: ruby-on-rails join has-and-belongs-to-many destroy

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

2 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:0)

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