【问题标题】:ecto jsonb array and map cast issueecto jsonb数组和地图转换问题
【发布时间】:2019-04-08 18:47:52
【问题描述】:

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

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

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】:

    解决方案是定义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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多