简体   繁体   中英

Rails nested jsonb query

i have active record object like this

`<BlockExercise id: 1, type: nil, user_id: 1, number: "S51_1", status: "close", exercise_distribution: {"Day1"=>{"BN3"=>"", "SQ1"=>"", "date"=>"10/03/2019"}, "Day2"=>{"BN2"=>"", "date"=>""}, "Day3"=>{"DL1"=>"", "date"=>""}, "Day4"=>{"DL2"=>"", "SQ2"=>"", "date"=>""}, "Day5"=>{"BN1"=>"", "date"=>""}}, created_at: "2019-03-15 18:59:02", updated_at: "2019-03-15 18:59:02"> `

Here column exercise_distribution is jsonb type. As this is a single object(row) and here is multiple keys(days) with uniq values. i want key(day) which has date present or not null. so here anser will be "Day1"=>{"BN3"=>"", "SQ1"=>"", "date"=>"10/03/2019"} how do i get this by sql query or any other suitable way.

This whole question is indicating that you are using JSONB where you should actually use the relational model and actually create a table which is an anti-pattern .

json is the new EAV – a great tool when you need it, but not something you should use as a first choice.

While you can query based on a JSONB column:

BlockExercise.where("(Day1->>'date' <> '') IS NOT TRUE")

The way your data structure is layed out its going to be really clunky since you have to do:

BlockExercise.where("(Day1->>'date' <> '') IS NOT TRUE")
             .where("(Day2->>'date' <> '') IS NOT TRUE")
             # ...

Joining records on the other hand is much simpler and more effective.

BlockExercise.joins(:exercise_distributions)
             .where.not(date: nil)

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