Records in join table destroyed automatically in HABTM association?
Asked Answered
F

2

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
Fid answered 16/2, 2011 at 17:4 Comment(0)
K
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
Katharinekatharsis answered 16/2, 2011 at 17:21 Comment(4)
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.Sheeree
HABTM requires an intermediate model/table otherwise the relation can't exist in a relational database. For the task that @Fid is attempting to accomplish he needs to either append to his existing RolesUser model or create it.Katharinekatharsis
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.Pleiad
Read this excellent post by shteef to learn more about additional attributes in a join table.Tusk
G
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

Gahl answered 4/4, 2016 at 0:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.