Search code examples
ruby-on-railsjsonruby-on-rails-3auditnamed-scope

How to write named scope for Audits which don`t have auditables?


I am using Audit gem in my Ruby on Rails application. I have used polymorphic association between Audits and my Orders.

Now, I want to write a named scope to get only those Audits for which Order is not deleted (This is happening because Order is being deleted after creating the Audit

<Audit id:110,
auditable_id:4,
auditable_type:"Order",
user_id:1,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-07 09:06:20">,
#<Audit id:49,
auditable_id:3,
auditable_type:"Order",
user_id:3,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-06 12:28:41">

Now when I enter Audit.first.auditable in my console, I get nil as order corresponding to that Audit is deleted and when I enter Audit.second.auditable I get order corresponding to second Audit.

I want to filter my Audit so that Audits of the type where order is deleted is removed(like Audit.first)


Solution

  • You can do it like this:

    Audit.rb

    scope :with_active_orders, -> { joins(:order) }
    

    Which will return Audits if there is at least one Order.