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

标签 ruby-on-rails json postgresql

我想用 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/

相关文章:

sql - 正确迁移 Postgres least() 行为到 BigQuery

python - postgresql/postgis 中的响应时间查询比较

postgresql - 如何在 jooq 中使用插入...返回语句作为 "table-like"查询?

mysql - 错误的迁移需要修复 mysql 表

json - 无法在electron-vue中获取本地json文件

javascript - jqgrid 日期时间格式化

java - Google 端点模型,如何使用 Parcelable、Serializable 或 JSON 字符串将数据发送到 Intent

mysql - 在 rake 任务中打开与 mysql 数据库的连接

javascript - Ruby on Rails - 无法使用 Java 脚本将第二个应用程序作为弹出窗口打开

ruby-on-rails - Docker 无法启动 rails