在作为数组的列上使用 WHERE 不起作用

using WHERE on a column that is an array is not working

我有一个 table,其中有一列是数组。 table 中的记录在 values 的列中具有数组 ["something","another thing"]。但是在执行 where 查询时,由于某种原因它们没有出现。所以我不确定我做错了什么。

# schema
t.text "values", default: "--- []\n"

# model
serialize :values, Array

# rails console
> Table.where(values: ["something","another thing"])
SELECT "tables".* FROM "tables" WHERE "tables"."values" IN ('something', 'another thing')
 => #<ActiveRecord::Relation []> 

所以我想要创建的理想 SQL 输出可能就像...

SELECT "tables".* FROM "tables" WHERE "tables"."values" = ?  [["values", ["something", "another thing"]]]

而不是数组似乎正在创建的 IN 查询

因为该列被序列化为数组,所以所需的值将存储为

"---\n- something\n- another thing\n"

在数据库中是一个字符串。

要通过 SQL 找到这样的记录,很遗憾,您将不得不依赖 LIKE

Table.where(["values LIKE ?", '%something\n- another thing%'])

如果两者之间可以有其他值或者顺序可以更改,您也必须考虑到这一点。也请承担我这样的查询对性能的影响

在序列化列上搜索是不应该做的事情。

我同意搜索序列化数据可能效率低下。 但这是我遇到的解决方案。

# model
scope :matching_values, -> (values) { where(matching_value_query(values, 'AND')) }
scope :subset_of_values, -> (values) { where(matching_value_query(values, 'OR')) }

def self.matching_value_query(values, condition_separator = 'OR')
  values.map { |value| "(values LIKE '%#{value}%')" }.join(" #{condition_separator} ")
end

# rails console
Table.matching_values(["something","another"])
 SELECT "tables".* FROM "tables" WHERE ((values LIKE '%something%') AND (values LIKE '%another%'))
=> #<ActiveRecord::Relation [ full of stuff ]