19
class Company
  has_and_belongs_to_many :users
end

class User
  has_and_belongs_to_many :companies
end

when i delete a company, what's the best (recommended) way to delete ONLY the associations of the users from that company? (i mean not the actual users, only the associations)

Andrei S
  • 6,486
  • 5
  • 37
  • 54

3 Answers3

19

I prefer the following since it keeps model logic in the model. I don't understand why ActiveRecord doesn't just do it. Anyway, in both joined models, I add the following callback.

before_destroy {|object| object.collection.clear}

So in your example:

class Company
  has_and_belongs_to_many :users
  before_destroy {|company| company.users.clear}
end

class User
  has_and_belongs_to_many :companies
  before_destroy {|user| user.companies.clear}
end

In a lot of discussions around doing a cascade delete on a collection association, many people declare the HABTM association dead and recommend has_many :through instead. I disagree. Use whatever makes sense. If the association has no intrinsic attributes, then use HABTM.

pduey
  • 3,706
  • 2
  • 23
  • 31
17

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many

collection.delete will do the trick.

theIV
  • 25,434
  • 5
  • 54
  • 58
  • 1
    @ShaChris23 I've updated the link to the latest available from the official API. I doubt they will remove `collection.delete` anytime soon, so that's probably the best link for it. Thanks for the heads up. – theIV Oct 03 '11 at 18:48
  • 1
    wheere should i call that? – Harsha M V Jun 21 '14 at 21:07
  • Using collection.clear is useful if you need to skip/bypass callbacks. – jBeas Aug 05 '15 at 16:13
12

If you call destroy instead of delete, associations will be deleted automatically.

Art Shayderov
  • 5,002
  • 1
  • 26
  • 33