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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With