如何使用 Geo 库创建有效的 Ecto 模型变更集?

2024-03-26

我正在尝试使用Geo https://github.com/bryanjos/geo通过 Phoenix 模型变更集存储 Geo.Point 的库。我的参数是:{coordinates: [49.44, 17.87]}或者更喜欢的是{coordinates: {latitude: 49.44, longitude: 17.87}}

在 iex 控制台中我尝试过:

iex(5)> changeset = Place.changeset(%Place{}, %{coordinates: [49.44, 17.87]})
%Ecto.Changeset{action: nil, changes: %{}, constraints: [],
 errors: [coordinates: "is invalid"], filters: %{}
 model: %Myapp.Place{__meta__: #Ecto.Schema.Metadata<:built>,
  coordinates: nil, id: nil, inserted_at: nil, updated_at: nil}, optional: [],
 opts: [], params: %{"coordinates" => [49.445614899999995, 17.875574099999998]},
 repo: nil, required: [:coordinates],

所有其他尝试均因 Poison.Parser 错误而结束。

应该如何从客户端查看参数来创建有效的变更集?

Model:

defmodule MyApp.Place do
  use MyApp.Web, :model

  schema "place" do
    field :coordinates, Geo.Point

    timestamps
  end

  @required_fields ~w(coordinates)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

根据库的测试:

https://github.com/bryanjos/geo/blob/351ee6c4f8ed24541c9c2908f615e7b0a238f010/test/geo/ecto_test.exs#L100 https://github.com/bryanjos/geo/blob/351ee6c4f8ed24541c9c2908f615e7b0a238f010/test/geo/ecto_test.exs#L100

您需要将 Geo.Point 传递给您的变更集函数:

changeset = Place.changeset(%Place{}, %{coordinates: %Geo.Point{coordinates: {49.44, 17.87}})

您可以在[文档]中阅读有关自定义 ecto 类型的更多信息。(https://hexdocs.pm/ecto/Ecto.Type.html#content https://hexdocs.pm/ecto/Ecto.Type.html#content)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Geo 库创建有效的 Ecto 模型变更集? 的相关文章

随机推荐