I am using Audit gem in my Ruby on Rails application. I have auditables like Order, Invoice for my Audits. My orders and Invoice model starts like this:-
class Order < ApplicationRecord
audited
has_associated_audits
Because of has_associated_audits, Audit[i].auditable will give me order/invoice corresponding to ith Audit. Now some of the Orders are deleted afterwards and Audit[i].auditable becomes nil. How do I get only those Audits for which Audit[i].auditable is not nil?
Because the Auditable relation is polymorphic, you can't just join the table and be on your way. Instead, you're going to need some raw SQL magic. This is an example using things from my own codebase, adjust to your needs:
Audited::Audit.joins('INNER JOIN titles ON audits.auditable_id = titles.id').where(auditable: nil, auditable_type: 'Title')
That was adapted from this great SO post here: ActiveRecord - querying polymorphic associations