11

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
zetetic
  • 47,184
  • 10
  • 111
  • 119
keruilin
  • 16,782
  • 34
  • 108
  • 175

2 Answers2

10

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
Pan Thomakos
  • 34,082
  • 9
  • 88
  • 85
  • 1
    I thought one of the points of HABTM was that there IS no intermediate model. So this wouldn't work unless the RolesUsers model existed. – ipd May 20 '11 at 20:56
  • HABTM requires an intermediate model/table otherwise the relation can't exist in a relational database. For the task that @keruilin is attempting to accomplish he needs to either append to his existing RolesUser model or create it. – Pan Thomakos May 23 '11 at 18:55
  • 6
    To clarify: HABTM requires the intermediate *table*, but not the extra model. You'll use `has_many/through` if you need extra controls or fields in the intermediate model. – ndp Jun 14 '12 at 20:09
  • Read [this excellent post by shteef](http://stackoverflow.com/a/2168528/356895) to learn more about additional attributes in a join table. – JJD Feb 01 '13 at 17:49
0

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

Ali
  • 261,656
  • 265
  • 575
  • 769