2014-02-19 45 views
2

我想基於序列化數組文本字段(Postgres,如果它很重要)執行Rails查找。所以:Rails通過序列化數組查找

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]] 

一切正常。但我似乎無法根據該字段進行查找:

> 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(或者我們?)是序列化的。所以讓我們嘗試:

> Foo.where(arr: [[1, 2], [3, 4]].to_yaml) 
=> #<ActiveRecord::Relation []> 

走近一看似乎導致我走向換行符爲什麼查找失敗的原因。我可以通過一個複雜的LIKE條款找到解決方法,但在那一點上,我認爲我可能走錯了路。

有沒有一種標準的方式來在Rails中查找基於序列化屬性的模型? (我應該只是序列化不是Yaml的東西?)非常感謝!

+1

呃。爲什麼不使用PostgreSQL的本地陣列支持?然後你可以使用它對數組索引的支持。 –

+0

因爲我需要存儲尺寸不斷變化的非正方形尺寸的多維數組。我的理解是Postgres不支持這一點,但絕對讓我知道如果它。 無論哪種方式,我不確定Rails在這種情況下會表現正確。 – JacobEvelyn

+0

確認它不是一個選項:'PG :: InvalidTextRepresentation:錯誤:多維數組必須具有匹配維度的數組表達式' – JacobEvelyn

回答

0

現在我使用的解決方案(肯定願意將其他方法!)很給力的Rails比YAML其他東西序列化,允許的串查詢:

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 

這是在一個小janky我必須使用自定義find_by_arr進行查詢,但它有效。

(編輯:刪除不好的示例代碼。)