Rails select_all 反序列化 Postgresql 数组

问题描述 投票:0回答:2

我做了一个自定义查询,返回具有数组值的行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 解析结果并返回嵌套数组?

ruby-on-rails ruby postgresql activerecord
2个回答
3
投票

你(我)应该调用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

0
投票

我也遇到了这个问题,所以我用 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
© www.soinside.com 2019 - 2024. All rights reserved.