2016-08-17 48 views
0

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

我得到了一个叫做问题模型,并包含一个序列化列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"] 

我需要找到谁包含至少一个group_id记录assignments

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

[ 
    { 
        :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) 

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

+0

你使用哪个数据库(postrgesql/mysql)?你使用哪个序列化器(JSON,Hash,Custom)?哪种类型是您的序列化列(文本,JSON,hstore)? – slowjack2k

+0

mysql,JSON和文本 –

回答

0

用mysql 5.7。?你可以直接查询JSON数据。我没有尝试,但遵照docs像

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

应该工作。您可以继续将文本转换为JSON数据类型的列,并获取JSON文档和优化存储的验证。

+0

我正在使用mysql 5.6,它看起来很难使用。我想我应该修改我的序列化列到许多属性。 –

+0

如果您必须通过SQL查询json数据,并且您的数据库不支持JSON查询,那么重构您的数据模型是一个不错的选择。 – slowjack2k