Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Records in join table destroyed automatically in HABTM association?

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
like image 500
keruilin Avatar asked Feb 16 '11 17:02

keruilin


1 Answers

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
like image 103
Pan Thomakos Avatar answered Sep 23 '22 09:09

Pan Thomakos