繁体   English   中英

如何在Ruby on Rails中使用PostgreSQL JSON数组查询ActiveRecord :: Relation

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

我想用51个字段查询ActiveRecord :: Relation。 数据结构是这样的:

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

要么

matings: {"ids"=>51}

如果我做:

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>
]>

我尝试使用MouseColony.where("CAST(matings ->> 'ids' AS TEXT) LIKE ?", "%51%")或使用MouseColony.where("matings ->> 'ids' = ?", "51") ,但结果是这样的MouseColony Load (1.0ms) SELECT "mouse_colonies".* FROM "mouse_colonies" WHERE (CAST(matings ->> 'ids' AS TEXT) LIKE '%51%') LIMIT $1 [["LIMIT", 11]] => #<ActiveRecord::Relation []>

我也尝试使用此方法:

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

但是仍然找不到任何数据。

我认为我的问题可能在这里:我的模型:mouse_colony.rb store :matings, :accessors => [:ids], coder: JSON :matings store :matings, :accessors => [:ids], coder: JSON ,我存储这样的记录: @mouse_colony.matings[:ids] = [50, 51, 64]`` @mouse_colony.save

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM