samedi 27 juin 2015

Filter ActiveAdmin with Postgresql json column on specific json keys

I have a Deal model that features a json column called deal_info. It's actually an array of JSONs.

I'm using active admin.

For example :

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

As first step now I would like to have a filter that would enable me to filter the deals based on the fact that deal_info json column includes at least one time the modal_id in one of its included json.

It would enable me in a select dropdown to choose for example modal_id = 6 and would filter the list of Deals to only show deal 1 (see example above).

One of the further challenge is that I need to be able to remove duplicates on the select dropdown in order not to have multiple times the same id: here for example i can't have select = [4,6,9,10,11,11]...each modal_id can only appear once.

I only found this but it did not work for me.

My current Active Admin Code

ActiveAdmin.register Deal do
  filter :modal_id,
  as: :select 
  collection: deal_info.all.to_a.map ???? 
end

EDIT after Andrei answer that helped move forward but not (yet) solve the problem

I added this code :

models/deal.rb

class Deal < ActiveRecord::Base
  store_accessor :deal_info, :modal_id
end

# using http://ift.tt/1LNYzLh
ransacker :modal_id do |parent|
   Arel::Nodes::InfixOperation.new('->', parent.table[:deal_info], 'modal_id')
 end

inside active admin Deal file

ActiveAdmin.register Deal do
     filter :modal_id,
     label: 'modal id',
     as: :select,
     collection: -> { Deal.all.pluck(:info_throbber).flatten.map {|el| el['modal_id'] }.uniq }

It seems to PARTLY work but not completely. Indeed it does show me on the dropdown the right various modal_id's and they are well de-duplicated BUT when I select one of them on the dropdown, and click FILTER on the right side (where the filter sidebar is), it load the whole page again WITHOUT applying the filter.

For example, on my modal_id dropdown, i have the chocie between ANY/4/5/8. If I choose modal_id 5 and click the FILTER button when the page with all the deals (that should be filtered on modal_id = 5) load, inside the sidebar modal_id select dropdown, I don't see 5 as I had chosen but ANY. The value of 5 was not "KEPT"/"REMEMBERED" and it got back to the value ANY. I don't understand why.

Aucun commentaire:

Enregistrer un commentaire