rails 3 habtm delete only association

后端 未结 3 672
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 02:08
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 (

3条回答
  •  无人及你
    2020-12-31 02:36

    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.

提交回复
热议问题