Searches in a jsonb column with key-value relationship with Ransack, where the values ​are objects

66 views Asked by At

I currently merge the ransack query with a query using .select to combine the search result with ransack with a custom search that I was unable to implement with it.

Basically, I have a column inside the "buyers" table called "click_identifier_data" which is a jsonb. Below is an example of a fictitious record for this column:

{"2023-10-20T11:11:31-03:00"=>{"utm_term"=>"int_test_123", "utm_medium"=>"jss", "utm_source"=>"test..."}, "2023-10-20T11:12:13-03:00"=>{"utm_compaign"=>"possible_campaign_123", "utm_source"=>"other_source", "utm_term"=>"5sa"}}

Saved fields are fields sent via cookie when a user registers on the website, therefore, it is possible (and quite likely) that there will be records that have different keys from each other.

Currently, the way the search is done in my controller is as follows:

utms = params[:utms].to_enum.to_h.reject { |_, v| v.blank? } unless params[:utms].blank?

@q = Buyer.active.ransack(params[:q])

@buyers = @q.result(distinct: true)

@buyers = @buyers.select { |buyer| buyer.click_identifier_data.values.any? { |utm_register| utms.all? { |key, value| utm_register[key] == value } } } unless utms.blank?

@buyers = @buyers.paginate(page: params[:page], per_page: h_per_page)

But I would like to couple this part of the query made with .select with the ransack itself, maintaining its functionality. How to do this?

0

There are 0 answers