Skip to content

Solution for filtering models having polymorphic belongs_to associations #1743

@vjt

Description

@vjt

Hi,

in order to have select-based index filters on models having a polymorphic belongs_to, I've hacked away the following new PolymorphicSelect input, leveraging MetaSearch multi-level associations syntax.

Given the model:

class Foo
  belongs_to :entity, :polymorphic => true
end

This input in app/admin/active_admin/inputs/filter_polymorphic_select_input.rb:

module ActiveAdmin::Inputs
  class FilterPolymorphicSelectInput < FilterSelectInput
    def initialize(*args)
      name, options = args.slice(4, 2)

      @_poly_type  = name
      @_poly_assoc = options[:on] or raise(":polymorphic_select needs the polymorphic association name in the :on option")

      super
    end

    # MetaSearch syntax for polymorphic associations
    def input_name
      "#{@_poly_assoc}_#{@_poly_type}_type_id_eq"
    end

  end
end

Referenced in a register block:

ActiveAdmin.register Foo do
  filter :bar, :as => :polymorphic_select, :on => :entity, :collection => proc { Bar.all }
  filter :baz, :as => :polymorphic_select, :on => :entity, :collection => proc { Baz.all }
end

Will yield two selects in the filters sidebar, behaving as you would expect, making MetaSearch generate where entity_type = "bar" and entity_id = 42.

There's still room for improvement, e.g. by automagically loading the :collection or automagically invoking the :polymorphic_select (with a better name) if the :on option is present and the reflection says it is a polymorphic association.

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions