Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter IS NULL in ActiveAdmin?

I've a table with an integer column called "map_id", I want to add an activeadmin filter to filter if this column IS NULL or IS NOT NULL.

How could this be implemented ?

I tried the following filter

filter :map_id, :label => 'Assigned', :as => :select, :collection => {:true => nil, :false => ''}

But, I get the following error message :

undefined method `map_eq' for #

like image 490
Mahmoud M. Abdel-Fattah Avatar asked Aug 20 '12 12:08

Mahmoud M. Abdel-Fattah


3 Answers

If anyone is happening on this thread belatedly, there is now an easy way to filter for null or non null in active admin :

filter :attribute_present, :as => :boolean 
filter :attribute_blank,   :as => :boolean  

It is no longer necessary to add a custom method to the scope to accomplish this.

like image 129
Avram Score Avatar answered Sep 23 '22 11:09

Avram Score


Not found a good solution but here is a how. filters of Active_admin are accomplished by meta_search, you can override the functions automatically generated by meta_search in your model to get the behavior that you want, the best way is to use the scope since you need to return a relation in order to chain with other query/scopes, as stated here

in your model:

for :as=>:select filters, acitve_admin use the _eq wheres, here is the source code

scope :map_eq, 
        lambda{ |id|
        if(id !='none')
            where( :map_id=> id)
        else
            where( :map_id=> nil)
        end
        }

#re-define the search method:
search_method :map_eq, :type => :integer

in your ative_admin register block:

filter :map_id, :label => 'Assigned', :as => :select, :collection => [['none', 'none'], ['one', 1],['tow', 2]]

# not using :none=>nil because active_admin will igore your nil value so your self-defined scope will never get chained.

Hope this help.

like image 29
Gret Avatar answered Sep 22 '22 11:09

Gret


seems search_method doesn't work in recent rails version, here is another solution:

add scope to your model:

  scope :field_blank, -> { where "field is null" }
  scope :field_not_blank, -> { where "field is not null" } 

add to /app/admin/[YOUR MODEL]

   scope :field_blank
   scope :field_not_blank

you will see buttons for these scopes appear (in top section, under model name, not in filter section)

like image 38
nazar kuliyev Avatar answered Sep 26 '22 11:09

nazar kuliyev