Search code examples
activerecordrails-activerecordpaper-trail-gem

Papertrail tracks create but not delete through association


I have a table of Industries and am keeping tracking of it's competitors which are also industries. This is through a mapping table industry_competitors which has industry_id and competitor_id. I want papertrail to track associations and dissociations of industry competitors.

class Industry < ApplicationRecord
  has_many :industry_competitors, dependent: :destroy
  has_many :competitors, through: :industry_competitors
end


class IndustryCompetitor < ApplicationRecord
  has_paper_trail
  belongs_to :industry
  belongs_to :competitor, class_name: "Industry"
end

My controller code is as such.

  competitors = ::Industry.where(id: params[:competitor_ids])
  @industry.competitors = competitors
  @industry.save

Every time the entire competitor list is passed. If I try to disassociate a few competitor (by not passing the ids to the controller) from the industry a 'Delete' query is fired.

  DELETE FROM `industry_competitors` WHERE `industry_competitors`.`industry_id` = 4559 AND `industry_competitors`.`competitor_id` = 4564

I suspect because activerecord calls 'delete' and not 'destroy' this papertrail callbacks are not triggered hence the changes are not tracked. If there a way to call delete explicitly (with minimal code changes). Or is there a way for papertrail to track delete?


Solution

  • Adding this patch can get it to work.

    module HasManyThroughAssociationPatch
      def delete_records(records, method)
        method ||= :destroy
        super
      end
    end
    
    ActiveRecord::Associations::HasManyThroughAssociation.prepend(HasManyThroughAssociationPatch)
    

    Credits: https://github.com/westonganger/paper_trail-association_tracking