Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inherited models don't fire audit events #677

Open
camerondrysdale opened this issue Jun 27, 2023 · 2 comments
Open

Inherited models don't fire audit events #677

camerondrysdale opened this issue Jun 27, 2023 · 2 comments

Comments

@camerondrysdale
Copy link

camerondrysdale commented Jun 27, 2023

I decided that it makes sense that the inherited model should fire audits against that model and not the parent and moved the logic to the original model with some conditionals instead.

@camerondrysdale
Copy link
Author

camerondrysdale commented Jul 7, 2023

I've re-opened this as it does pose an interesting issue, so curious what the options are...

If you have a model setup like this:

class Collection < ApplicationRecord
  has_many :products

  audited
  has_associated_audits
end

class Product < ApplicationRecord
  belongs_to :collection

  audited associated_with: :product
end

class AnotherProduct < Product
  # some logic specific to AnotherProduct
end

When ever the Product or Collection is updated it will log the changes and these can be accessed from the Collection with:

@collection = Collection.first
@collection.own_and_associated_audits

However, if you were to do an update on the AnotherProduct model, you would see audits against that model:

@another_product = AnotherProduct.update(update_params)
@another_product.audits.present? => true

This makes sense, in that it was AnotherProduct that had the changes against it made... even though it inherits from the Product model. But it means you can't see those audits with:

@product = Product.where(name: 'AnotherProduct').first
@product.audits

Even though the record is the same, but the object in which the audit is associated is different, so it means you can't retrieve the audits, and also then means you can't see them against the collection itself.

Is there a way to get around this? Perhaps trick Audited into seeing the model name as something different? or perhaps being able to join inherited models somehow when pulling back the audit records?

@camerondrysdale
Copy link
Author

I was having a look at that method own_and_associated_audits:

def own_and_associated_audits
  Audited.audit_class.unscoped.where(auditable: self)
  .or(Audited.audit_class.unscoped.where(associated: self))
  .order(created_at: :desc)
end

Perhaps that can be monkey-patched to pull through associated inherited models too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant