2

Looking for the right way to setup audited associated_with and has_associated_audits in my models its easier to track.

The Setup: Publisher has exclusive dealer with Authors. An author can write many books. A Book can have many writers. A Book has one type of book binding. A book binding can have many books.

Goal: Id like to be able to call Publisher.find(1).associated_audits to get everyone in one fail swoop.

class Publisher < ActiveRecord::Base
  audited
  has_associated_audits

  has_many :books
end

class Author < ActiveRecord::Base
  audited associated_with: :publisher
  has_associated_audits

  belongs_to :publisher
  has_many :author_to_books
  has_many :books, through: :author_to_books
end

class AuthorToBook < ActiveRecord::Base
  audited associated_with: #????? this is where I need help
  has_associated_audits

  belongs_to :book
  belongs_to :author
end

class Book < ActiveRecord::Base
  audited associated_with: #????? this is where I need help
  has_associated_audits

  has_many :author_to_books
  has_many :authors, through: :author_to_books
  belongs_to :book_binding_type
end

class BookBindingType < ActiveRecord::Base
  audited associated_with: #????? this is where I need help
  has_associated_audits

  has_many :books
  has_many :publishers, through: :books
end

Currently I can call Publisher.find(1).associated_audits and that gives me the associated audits for Author.

For Book I do: Book.joins(:audits).references(:audits).joins(:authors).where(authors: {publisher_id: 1}).map(&:audits)

For BookBindingType I do Book.joins(:audits).references(:audits).joins(:authors).where(authors: {publisher_id: 1}).map(&:audits)

As you can guess those last two queries, while taking into consideration time complexities...they both still take a bit of time to run when I start having more records.

The Question: How can I setup the ???? parts of the audited gem to able to track. I know the polymorphic setup of the audits table only allows it to track one associated record at a time. So is it even possible?

cal1801
  • 135
  • 1
  • 11

1 Answers1

1

For the few people that have looked; I haven't found an official associated_with: way of doing it. However I have dramatically increased the the processing time involved by directly querying the Audits table. I will eventually extend the Audits model with my own custom audit model, but for now I am doing:

Audited::Audit.where(auditable_type: 'BookBindingType', auditable_id: BookBindingType.joins(:publishers).where(publishers: {id: 1}))

This runs the query much quicker than the includes/joins I used in my question's description.

cal1801
  • 135
  • 1
  • 11