简体   繁体   中英

Rails ransack gem to search jsonb column with key value pair as parameter

How to properly search on JSONB column, passing key & value as params.

Following this wiki https://github.com/activerecord-hackery/ransack/wiki/PostgreSQL-JSONB-searches .

Everything works for me except the bottom part, where said that we can search also by passing key value.

ransacker :within_json do |parent|
   Arel.sql("contacts.json_data::text") 
end

Like: Contact.all.ransack("within_json_cont" => '{"key": "value"}') But can make it work, no result for me.

Remove the curly braces, since it represents the complete hash. You need to get json data containe a specific key and value.

ransacker :within_json do |parent|
   Arel.sql("contacts.json_data::text") 
end

This part is correct if you are using PostgreSQL. If you are using MySQL you can do it like

ransacker :within_json do |parent|
   Arel.sql("contacts.json_data") 
end

These data is stored as text in database, so we just need to search for exact text. This can be done by

Contact.ransack("within_json_cont" => '"key":"value"')

And if you want to search for specific value for a key, you can create a ransacker

  ransacker :key do |parent|
    Arel::Nodes::InfixOperation.new('->>', parent.table[:json_data],
                                    Arel::Nodes.build_quoted('$.key'))
  end

Hope this helps. Good luck

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