简体   繁体   中英

Filter by serialized attribute using ActiveAdmin

I'm using ActiveAdmin and I need to build a custom filter, a combobox with abilities to filter users index list. For example:

<select>
   <option value="designer">Diseñador</option>
   <option value="developer">Desarrollador</option>
   <option value="manager">Jefe de Proyecto</option>
</select>

I have users...

#<User id: 1, email: "un@tipo.com", abilities: {"designer"=>"Some comment", "developer"=>"Other comment", "manager"=>"Another comment"}>
#<User id: 2, email: "otro@tipo.com", abilities: {"designer"=>"blah blah"}>

As you can see, abilities attribute is defined on User model as:

serialize :abilities, Hash

So, when in the combobox I select designer I want to see two users on the list. If instead I choose manager I want to see one user .

I know that ActiveAdmin uses ransack to build filters but I don't know how to use this to work with serialized attributes.

I tried to use ransacker with the following code:

ActiveAdmin :

ActiveAdmin.register User do  
  filter :by_ability, as: :string, collection: ['designer', 'other']

Model :

class User < ActiveRecord::Base
  scope :by_ability_eq, lambda {|v| User.where(["users.abilities LIKE '%?%'", v]) }
  ransacker :by_ability_eq

but I get this error :

undefined method `by_ability_eq' for Ransack::Search<class: User, base: Grouping <combinator: and>>:Ransack::Search

I think this should work

ActiveAdmin.register User do  
  filter :abilities_contains, as: :select, collection: ['designer', 'other']
  #....
end

In this case you don't need scope in model

UPD

IF you need only keys to search, and your serializator uses YAML, you can try to customize it with something like

collection:  [["designer", "designer:"], ["other","other:"]]

Than it will use "designer:" and "other:" to search with LIKE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM