ecto jsonb数组和地图转换问题

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

我想使用jsonb存储数据,可以是数组或映射。源数据作为数组或映射到达,我们希望在服务器上统一这一点,以便前端可以使用单一类型。有没有一种方法/解决方法,我可以使用,存储和检索json / map和对jsonb postgres类型有效的数组类型?

如果我在source:中得到一个数组,我已经尝试使用sourced复制到数组类型params字段,然后调用转换管道:

condition: Map.has_key?(params, "value") && is_list(value)

我成功地能够保存数据,但是当从数据库中检索时,我收到了一个强制转换错误

field(:value, :map)
field(:value_array, {:array, :integer}, source: :value)

注意:Ecto版本> 3和postgres 10

postgresql elixir ecto jsonb
1个回答
0
投票

解决方案是定义custom ecto types,它将接受并加载数组和映射

defmodule HaiData.Jsonb do
  @behaviour Ecto.Type
  def type, do: :map

  # Provide custom casting rules.
  def cast(data) when is_list(data) or is_map(data) do
    {:ok, data}
  end


  # Everything else is a failure though
  def cast(_), do: :error

  # When loading data from the database, we are guaranteed to
  # receive a map or list
  def load(data) when is_list(data) or is_map(data) do
    {:ok, data}
  end

  # When dumping data to the database, we *expect* a map or list
  # so we need to guard against them.
  def dump(data)  when is_list(data) or is_map(data), do: {:ok, data}
  def dump(_), do: :error
end

归功于idiot - an elixirforum user

© www.soinside.com 2019 - 2024. All rights reserved.