2015-11-23 16 views
6

我正在嘗試使用Geo庫通過Phoenix模型變更集來存儲Geo.Point。我的PARAMS是:{coordinates: [49.44, 17.87]}或更多傾向於將{coordinates: {latitude: 49.44, longitude: 17.87}}如何使用地理庫創建有效的Ecto模型變更集?

在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錯誤結束所有其他的嘗試。

客戶端應該如何查看params來創建有效的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 

回答

5

據該庫的測試:

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

+0

你能告訴我如何將'{座標:{緯度:49.44,經度:17.87}}'以'格式'提取'緯度經度'到'%Geo.Point {}'? – luzny

+2

'%Geo.Point(座標:{get_in(coords_map.coordinates.latitude),get_in(coords_map.coordinates.longitude)})'http://elixir-lang.org/docs/stable/elixir/Kernel.html# get_in/2 – Gazler

+0

當我有更多的參數,如'coords_map =%{name:「test」,座標:%{latitude:49.44,longitude:17.87}}'我想將%Geo.Point連接到座標參數,它有一些簡單的方法? – luzny

相關問題