0

I am running into a roadblock and this SO question's second answer gets me so close!

Using postgresql I have a jsonb, places, on my orders table with the following shape:

[
 { "delivery_place" : { "id" : "abc", "name" : "my place" } },
 { "delivery_place" : { "id" : "xyz", "name" : "your place" } }
]

My goal is to use an ILIKE to query the "name" details to retrieve the correct orders. Normally I would do that with:

select id from orders, jsonb_array_elements(orders.places) as places where places -> 'delivery_place' ->> 'name' ILIKE '%my%'

I am using Rails 6 and already have a .from() clause defined and can not easily overwrite it for an optional search criteria. So I am trying to figure out how to do this with just the where clause.

The linked post above seems to get me 90% of the way there by using the @> operator. Thus I could do select id from orders where orders.places @> '["delivery_place" : {"name": "my place"}]' However I can't figure out how to combine this with an ILIKE.

Is this even possible? If not, is there a way that I am just not noticing? Trying ot use the jsonb_array_elements in the where directly gave me an error but perhaps there is a way? If not does anyone know any resources for learning how to use with clauses in Rails 6?

3
  • Unrelated to your Rails problem, but the plain SQL query would be more efficient using from orders where exists (select * from jsonb_array_elements(...) where ... ILIKE ...) Commented Nov 30, 2020 at 7:00
  • I think you just saved me so much headache. I quick try of doing a where exists (select...) worked well for me. I will have to implement in full and test but this may have just answered my question! Thank you so kindly! Commented Nov 30, 2020 at 7:30
  • Yep, that worked like a charm! Thanks again! Feel free to make it a real answer reply and I can +1 it! Commented Nov 30, 2020 at 9:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.