Audit deep associations with Rails Audited gem

2.6k Views Asked by At

I have the next three models:

class School < ActiveRecord::Base
  audited
  has_associated_audits

  has_many :subjects, dependent: :destroy
end

class Subject < ActiveRecord::Base
  audited associated_with: :school
  has_associated_audits

  has_many :attachments, as: :attachable, dependent: :destroy
end

class Attachment < ActiveRecord::Base
  audited associated_with: :attachable
  belongs_to :attachable, polymorphic: true
end

Basically, A school has many subjects, and each subject has many attachments (the attachment model is polymorphic because it's used for other models too, just in case it matters...)

The problem is that the audit is not working as I expect. I create a school, then a subject for that school, and then I add attachments to that subject. This is what I get from the console:

School.last.associated_audits # => returns only changes on Subjects, not on subject's attachments.
Subject.last.associated_audits # => returns only changes associated to its attachments

But I would need is School.last.associated_audits to include attachments audited changes too.

Any ideas?

2

There are 2 best solutions below

0
On

The audited gem now has a helper method:

You can access records' own audits and associated audits in one go:

company.own_and_associated_audits
0
On

While you're not able to retrieve audits from deep associations, you could group the audits together. For example:

school = School.find(params[:id])
audits = school.audits + school.associated_audits
school.subjects.each { |subject| audits += subject.associated_audits }

I believe this should give you the entire collection of audits for School, Subject and Attachments. Is this sort of what you were after?