Rails select_all反序列化Postgresql数组



我进行了一个自定义查询,返回具有数组值term_names的行

Product.connection.select_all("
SELECT ARRAY_AGG(terms.name), vocabularies.name vocabulary_name
FROM terms
INNER JOIN vocabularies ON vocabularies.id = terms.vocabulary_id
GROUP BY vocabulary_name")
| term_names                                                     | vocabulary_name |
|----------------------------------------------------------------|-----------------|
| {{76,Yellow},{77,Green},{79,Blue}.                             | Color           |

但问题是Rails不希望将{…}转换为ruby数组并将其作为字符串返回。

[{"array_agg"=>"{Yellow,Green,Blue}", "vocabulary_name"=>"Color"}]

如何让Rails解析结果并返回嵌套数组?

您(我(应该调用cast_values方法

Product.connection.select_all("
SELECT ARRAY_AGG(terms.name), vocabularies.name vocabulary_name
FROM terms
INNER JOIN vocabularies ON vocabularies.id = terms.vocabulary_id
GROUP BY vocabulary_name").cast_values

我也遇到了这个问题,所以我用to_cast_hash方法扩展了ActiveRecord::Result

class ActiveRecord::Result
# NOTE: calling .to_hash turns all values, including arrays, into strings, 
# while calling .cast_values returns an array without the column keys.
# This method returns a hash of the results with properly cast values:
def to_cast_hash
cast_rows = self.cast_values
cols = self.columns
cast_hashes = []
cast_rows.each do |row|
h = {}
cols.each_with_index do |col,index|
h[col] = row[index]
end
cast_hashes.push(h)
end
return cast_hashes
end

end

最新更新