rails 3 habtm delete only association

那年仲夏 提交于 2019-11-29 11:14:57

问题


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)


回答1:


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

collection.delete will do the trick.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/4994245/rails-3-habtm-delete-only-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!