简体   繁体   中英

How to use the PostgreSQL JSON array query ActiveRecord::Relation in Ruby on Rails

I want to query ActiveRecord::Relation with 51 fields. the data structure is like this:

matings: {"ids"=>[50, 51, 64]}

or

matings: {"ids"=>51}

If I do:

MouseColony.where("CAST(matings AS TEXT) LIKE ?", "%51%")

=>#<ActiveRecord::Relation [
  #<MouseColony id: 604, animal_no: "a0008", animal_desc: "", gender: "M♂", source: "外购", animal_status: "配对", cage_id: nil, generation: 0, birth_date: "2018-12-25", weaning_date: "2019-01-15", disable_date: nil, received_date: "2019-03-20", created_at: "2019-06-03 02:45:03", updated_at: "2019-06-03 03:14:37", user_id: 1, strain_id: 1, mating_id: 64, litter_id: nil, purchase_mouse_number: "17203", age: 223, mating_quantity: 3, matings: {"ids"=>[50, 51, 64]}, genotype_id: 10, experiment_id: nil, experiment_date: nil, age_weeks: 32>, 
  #<MouseColony id: 624, animal_no: "a0028", animal_desc: "", gender: "F♀", source: "外购", animal_status: "配对", cage_id: nil, generation: 0, birth_date: "2018-12-25", weaning_date: "2019-01-15", disable_date: nil, received_date: "2019-03-20", created_at: "2019-06-03 02:50:07", updated_at: "2019-06-03 03:09:11", user_id: 1, strain_id: 1, mating_id: 51, litter_id: nil, purchase_mouse_number: "17138", age: 223, mating_quantity: 5, matings: {"ids"=>51}, genotype_id: 9, experiment_id: nil, experiment_date: nil, age_weeks: 32>
]>

I tried to use MouseColony.where("CAST(matings ->> 'ids' AS TEXT) LIKE ?", "%51%") or using MouseColony.where("matings ->> 'ids' = ?", "51") , but the result is such a MouseColony Load (1.0ms) SELECT "mouse_colonies".* FROM "mouse_colonies" WHERE (CAST(matings ->> 'ids' AS TEXT) LIKE '%51%') LIMIT $1 [["LIMIT", 11]] => #<ActiveRecord::Relation []>

I've also tried to use this:

MouseColony.where("matings #>> '{ids}' = ?", "51")

But still can't find any data.

I think my problem might be here: My models: mouse_colony.rb store :matings, :accessors => [:ids], coder: JSON and I storage record like this: @mouse_colony.matings[:ids] = [50, 51, 64]`` @mouse_colony.save

您可以尝试使用“包含”运算符@>

MouseColony.where("matings->'ids' @> '?'", 51)

您应该能够像这样使用LIKE运算符:

MouseColony.where("matings::json->>'ids' LIKE ?", "%51%")

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