rog*_*rgl 3 elixir ecto phoenix-framework
IO.puts(inspect(contacts))给出:
[%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>}]
Run Code Online (Sandbox Code Playgroud)
视图看起来像:
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
IO.puts(inspect( contacts ))
contacts
end
end
Run Code Online (Sandbox Code Playgroud)
一旦我尝试渲染这个视图,我得到:
** (Poison.EncodeError) unable to encode value: {nil, "contacts"}
Run Code Online (Sandbox Code Playgroud)
您需要实现Poison.Encoder
协议,HelloTable.Contact
如在elixir中将Ecto模型编码为JSON中所述,或者使用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
Run Code Online (Sandbox Code Playgroud)
以上是在Phoenix JSON生成器中处理JSON的方法.
归档时间: |
|
查看次数: |
3243 次 |
最近记录: |