Adding custom filters on active admin using Ransacker

Scenario for below code…
Customer placing orders for a several line items of a vendor in a shopping website..
Tables : Order (has many line items)
line item (belongs to vendor)

Following is the code for filter by vendor on order’s page (Note: order table is not directly related with vendor, there can be multiple vendors involved on a single order. Order table does not have vendor_id and similarly vendor table not having order_id. But line_items table have order_id and vendor_id stored, so this needs to customized at it’s best)

filter :vendor_in,
:as => :select,
:label => ‘Vendor’,
:collection => proc {{ |vendor| [vendor.username,] }.uniq }

ransacker :vendor,
formatter: proc { |selected_vendor_id|
results = Order.has_vendor(selected_vendor_id).map(&:id)
results = results.present? ? results : nil
}, splat_params: true do |parent|

# Executes the query which fetches the orders of selected vendor
def self.has_vendor(vendor_id)
self.joins(:line_items).where(“line_items.vendor_id = ?”, vendor_id).uniq

That’s it you are done!