Rails通过序列化数组查找 [英] Rails look up by serialized array
问题描述
我正在尝试基于序列化的数组文本字段(如果需要的话,请使用Postgres)执行Rails查找。因此:
I'm trying to perform a Rails lookup based on a serialized array text field (Postgres, if it matters). So:
class Foo < ActiveRecord::Base
serialize :arr, Array
end
然后:
> f = Foo.create!(arr: [[1, 2], [3, 4]])
=> #<Foo id: 1, arr: [[1, 2], [3, 4]]>
> f.arr
=> [[1, 2], [3, 4]]
一切顺利。但我似乎无法根据该字段进行查找:
All's well. But I can't seem to do a lookup based on that field:
> Foo.where(arr: [[1, 2], [3, 4]])
=> ActiveRecord::StatementInvalid Exception: PG::UndefinedFunction: ERROR: operator does not exist: text = integer
"foos"."arr" IN (1, 2, ...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Rails似乎正在尝试将其转换为IN查询。无论如何,我们知道Rails是使用Yaml序列化的(还是我们?)。让我们尝试:
It seems Rails is trying to convert it into an IN query. No matter, we know Rails serializes with Yaml (or do we?). So let's try:
> Foo.where(arr: [[1, 2], [3, 4]].to_yaml)
=> #<ActiveRecord::Relation []>
更仔细的检查似乎使我转向换行符,因为此查找失败的原因。我可以找到一个带有复杂LIKE子句的解决方法,但那时候我想我可能走错了路。
Closer inspection seems to lead me towards newlines as the reason why this lookup fails. I could find a way around this with a complex LIKE clause but at that point I think I'm probably headed down the wrong path.
有没有一种查找模型的标准方法在Rails中基于序列化的属性(我应该使用不是Yaml的东西进行序列化吗?)非常感谢!
Is there a standard way to look up a model in Rails based on a serialized attribute? (Should I just serialize with something that isn't Yaml?) Many thanks!
推荐答案
我目前使用的解决方案(肯定对其他方法开放!)是强制Rails使用Yaml之外的其他东西进行序列化,以允许进行字符串查询:
The solution I'm using for now (definitely open to other approaches!) is to force Rails to serialize with something other than Yaml, to allow for string queries:
class Foo < ActiveRecord::Base
serialize :arr, SerializedArray
def self.find_by_arr
self.where(arr: SerializedArray.dump(arr)).take
end
end
class SerializedArray
def self.load(arr)
arr ? JSON.load(arr) : nil
end
def self.dump(arr)
arr ? JSON.dump(arr) : nil
end
end
有点简直就是我必须使用自定义 find_by_arr
进行查询,但是它可以工作。
It's a little janky in that I have to query with the custom find_by_arr
, but it works.
(编辑:删除了错误的示例代码。)
( removed bad example code.)
这篇关于Rails通过序列化数组查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!