[50, 51, 64]} 或 matings: {"ids"=>51} 如-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:28:04 25 4
gpt4 key购买 nike

我想用 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 我这样存储记录: @mouse_colony.matings[:ids] = [50, 51, 64]`` @mouse_colony.save

最佳答案

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

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

关于ruby-on-rails - 如何在 Ruby on Rails 中使用 PostgreSQL JSON 数组查询 ActiveRecord::Relation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com