3

I want to query ActiveRecord collection and select records, where string value inside jsonb field is included in a given array.

Model:

create_table "dishes", force: :cascade do |t|
    ...
    t.jsonb     "params"
    ...
end

Content of params always has this structure:

{"procart_id"=>"4", "procart_config"=>{}}

I have a given array:

availabilities = ['4', '8', '11']

How can I query Dish models where params.procart_id is in availabilities array?

I tried the following:

Dish.where("params::jsonb ->> 'procart_id' = any (array[?])", availabilities)

But it gave me the error:

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type json
DETAIL:  The input string ended unexpectedly.
CONTEXT:  JSON data, line 1: 
: SELECT "dishes".* FROM "dishes" WHERE (params::jsonb ->> 'procart_id' = any (array['4', '8', '11']))
5
  • 1
    It works in Postgres. Commented Dec 21, 2022 at 8:13
  • 1
    What version of Postgres and Rails, please? Commented Dec 21, 2022 at 8:16
  • @Schwern Postgres 9.4 and Rails 4.2.0 Commented Dec 21, 2022 at 8:17
  • 1
    Those are both quite old, but it does work in Postgres 9.4. Commented Dec 21, 2022 at 8:19
  • @Schwern ye, quite old 😅 Strange, the snippet does really work, but doesn't on my machine. Maybe I've missed something, will investigate. Thanks. Commented Dec 21, 2022 at 8:27

2 Answers 2

3

Dish.where("params::jsonb ->> 'procart_id' = any (array[?]::jsonb[])", availabilities)

Try this..it might work

Sign up to request clarification or add additional context in comments.

1 Comment

Removing the ::jsonb[] after the any from this solution worked for me. Ruby 3.2.0, PGSQL 13.
-1

You can modify the query params before querying the Dish model and query on procart_id like below:

availabilities = ['4', '8', '11']
query_params = availabilities.map { |availability| { procart_id: availability } }
Dish.where(params: query_params)

Comments

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.