【问题标题】:Search in rails serialize column在 Rails 序列化列中搜索
【发布时间】:2016-08-17 10:20:03
【问题描述】:

我知道在serialize 中搜索不好,但我遇到了这个问题。

我有一个名为 Question 的模型并包含一个序列化列 assignments

id question_set_id  assignments
1   1               {"12982": true, "12332": true}
2   2               {"12222": true, "12332": true}
3   3               {'11111': true}

我得到了一个名为group_ids的数组

group_ids = ["12982","12332"] 

我需要在assignments中找到至少包含一个group_id的记录。

所以,这个例子的结果应该是这样的

[
    {
                     :id => 1,
        :question_set_id => 1,
            :assignments => {"12982": true, "12332": true}
    },
    { 
                     :id => 2,
        :question_set_id => 2,
            :assignments => {"12222": true, "12332": true}
    }
]

我试过了

Question.where("assignments IS NOT NULL").where("assignments LIKE '%?%'", 12982)

似乎可行,但如何应用数组?

根据这个answer,我试过了

Question.where("assignments IS NOT NULL").where("assignments= ?", groups_ids.to_yaml)

但是,它返回一个空白数组。

【问题讨论】:

  • 你使用哪个数据库(postrgesql/mysql)?您使用哪个序列化程序(JSON、哈希、自定义)?您的序列化列是哪种类型(Text、JSON、hstore)?
  • mysql、JSON 和文本

标签: ruby-on-rails activerecord serialization


【解决方案1】:

使用 mysql 5.7.?您可以直接查询 JSON 数据。我没有尝试过,但按照文档类似

Question.where("JSON_CONTAINS_PATH(assignments , 'one', '$[*].assignments.12982', '$[*].assignments.12332') == 1")

应该可以。您可以进一步将列从文本转换为 JSON 数据类型,并获得 json 文档的验证和优化的存储。

【讨论】:

  • 我用的是mysql 5.6,看起来很难用。我想我应该将我的序列化列修改为许多属性。
  • 如果您必须通过 SQL 查询 json 数据,而您的数据库不支持 JSON 查询,那么重构您的数据模型是一个不错的选择。
猜你喜欢
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多