Skip to content

Prevent wrong destroy behaviour when overriding ActiveRecord association

Background

If the :through option is used, then the join records are destroyed instead, not the objects themselves.

-- source

Problem

Overriding has_many :through could change this destroy behaviour depending on what the overridden method returns.

Usually a has_many :through association is a ActiveRecord::Associations::CollectionProxy which has its own destroy method

If you override the association to return a Relation instead, then that will end up destroying the wrong record.

  1. Confirm this is true, or not #424307 (comment 1547900326)
  2. Add a spec or Rubocop to disallow overriding has_many :through association - #424307 (comment 1547127032)
  3. Fix existing cases

Known cases

From #424307 (comment 1547642461):

  • [[:remediations, ["/Users/omar/gdk/gitlab/ee/app/models/vulnerabilities/finding.rb", 259]]]
  • [[:group_users, ["/Users/omar/gdk/gitlab/ee/app/models/concerns/approval_rule_like.rb", 60]]]. Fixed in !131006 (merged)
  • [[:assignees, ["/Users/omar/gdk/gitlab/app/models/concerns/deprecated_assignee.rb", 45]]]
  • [[:users, ["/Users/omar/gdk/gitlab/app/models/group.rb", 344]]]. Fixed in !131006 (merged)
  • [[:authorized_projects, ["/Users/omar/gdk/gitlab/app/models/user.rb", 1149]]]

/cc @manojmj @OmarQunsulGitlab @dblessing @arturoherrero

Edited by Thong Kuah