2015-10-22 54 views
3

IO.puts(檢查(接觸))的列表給出(Poison.EncodeError)給出:返回無法編碼值

[%HelloTable.Contact{__meta__: #Ecto.Schema.Metadata<:loaded>, 
id: 37, 
inserted_at: #Ecto.DateTime<2015-10-22T12:50:43Z>, 
name: "Gumbo", phone: "(801) 555-55555", 
updated_at: #Ecto.DateTime<2015-10-22T12:50:43Z>}] 

和視圖的樣子:

defmodule HelloTable.ContactView do 
    use HelloTable.Web, :view 

    def render("index.json", %{contacts: contacts}) do 
    IO.puts(inspect(contacts)) 
    contacts 
    end 

end 

只要我試圖使這個觀點我得到:

** (Poison.EncodeError) unable to encode value: {nil, "contacts"} 

回答

4

你要麼需要實現Poison.Encoder協議HelloTable.ContactEncoding a Ecto Model to JSON in elixir描述或返回來自使用render_many/4渲染功能的地圖:

defmodule HelloTable.ContactView do 
    use HelloTable.Web, :view 

    def render("index.json", %{contacts: contacts}) do 
    render_many(contacts, __MODULE__, "contact.json") 
    end 

    def render("contact.json", %{contact: contact}) do 
    %{ 
     id: contact.id, 
     name: contact.name, 
     phone_number: contact.phone 
    } 
    end  
end 

以上是如何JSON與在Phoenix JSON generators處理。

+0

感謝,它的工作原理,只是缺少接觸後逗號。名稱。 –

0

this response to a similar question中描述了使用更新版本的毒藥的另一個更清潔的解決方案。

這行代碼添加到您的模型:

@derive {Poison.Encoder, only: [:name, :phone]} 

(也可以包括:的updated_at如果你想包括在您的JSON場)