Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activeadmin: how to filter for strings that match two or more search terms

Let's say I've got User class with an :email field. And let's say I'm using activeadmin to manage Users.

Making a filter that returns emails that match one string, e.g. "smith", is very simple. In admin/user.rb, I just include the line

filter :email 

This gives me a filter widget that does the job.

However, this filter doesn't let me search for the intersection of multiple terms. I can search for emails containing "smith", but not for emails containing both "smith" AND ".edu".

Google tells me that activerecord uses Ransack under the hood, and the Ransack demo has an 'advanced' mode that permits multiple term searches.

What's the easiest way to get a multiple term search widget into activeadmin?

Ideally, I'd like a widget that would allow me to enter smith .edu or smith AND .edu to filter for emails containing both terms.

like image 548
dB' Avatar asked Oct 23 '15 19:10

dB'


1 Answers

there is simple solution using ranasckable scopes

So put something like this in your model

class User < ActiveRecord::Base
    ....
    scope :email_includes, ->(search) {
       current_scope = self
       search.split.uniq.each do |word|
         current_scope = current_scope.where('user.email ILIKE ?', "%#{word}%")  
       end
       current_scope
    }

    def self.ransackable_scopes(auth_object = nil)
      [ :email_includes]
    end
end

After this you can add filter with AA DSL

Like

  filter :email_includes, as: :string, label: "Email"

UPD

should work if change email_contains_any to email_includes

like image 163
Fivell Avatar answered Nov 04 '22 07:11

Fivell