0

So I have this model Foo with nested fields,

<id: 1, name: "blah", condition: "{\"condition_type\":\"BAR\",\"number\":\"1\""\}">

I want to get the list of Foos with condition type Bar only. I have tried

    JSON.parse(Foo.select(:condition)).where({"condition_type"=>"BAR"})

but doesn't work. I would appreciate any help!

0

1 Answer 1

1

There's a slight syntax error in your JSON (I think an extra quote at the end but at the end of JSON.parse(Foo.select(:condition)) you're now working with a JSON object (which I think you're aware of. If you were to say:

JSON.parse(Foo.select(:condition)).class you would get a hash.

[12] pry(main)> json
=> {"condition_type"=>"BAR", "number"=>"1"}
[13] pry(main)> json.class
=> Hash

That all said, you can use the the Enumerable#keep_if method like this on a hash:

[26] pry(main)> json = JSON.parse(condition)
=> {"condition_type"=>"BAR", "number"=>"1"}
[27] pry(main)> json.keep_if { |k, v| k == "condition_type" && v == "BAR" }
=> {"condition_type"=>"BAR"}

The combined method would look like this:

JSON.parse(Foo.select(:condition)).keep_if { |k, v| k == "condition_type" && v == "BAR" }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot it helped!! but I was wondering if there is any simpler way of doing it without using blocks, just by using query commands.
are you storing the json as a text field in your database? If so what database?

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.