如何使用地理库创建有效的Ecto模型变更集? [英] How to use Geo library to create valid Ecto Model changeset?
问题描述
我正在尝试使用 Geo 库通过Phoenix模型更改集存储Geo.Point.我的参数是:{coordinates: [49.44, 17.87]}
或更喜欢的是{coordinates: {latitude: 49.44, longitude: 17.87}}
I'm trying to use Geo library to store Geo.Point via Phoenix model changeset. My params are: {coordinates: [49.44, 17.87]}
or more prefer would be {coordinates: {latitude: 49.44, longitude: 17.87}}
在iex控制台中,我尝试过:
In iex console I tried:
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错误结束.
All other attempts ended by Poison.Parser errors.
应该如何从客户端看参数来创建有效的变更集?
How should looks params from client side to create valid changeset?
型号:
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
推荐答案
根据该库的测试:
您需要将Geo.Point传递给变更集函数:
You need to pass a Geo.Point to your changeset function:
changeset = Place.changeset(%Place{}, %{coordinates: %Geo.Point{coordinates: {49.44, 17.87}})
您可以在[docs]中了解有关自定义ecto类型的更多信息.( https://hexdocs.pm/ecto/Ecto.Type.html#content )
You can read more about custom ecto types in [the docs].(https://hexdocs.pm/ecto/Ecto.Type.html#content)
这篇关于如何使用地理库创建有效的Ecto模型变更集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!