【发布时间】:2014-11-06 16:07:36
【问题描述】:
我想从 phoenix 中的 ecto 关联生成 JSON。
这是我的协会:
defmodule Blog.Post do
use Ecto.Model
schema "posts" do
field :title, :string
field :body, :string
has_many :comments, Blog.Comment
end
end
和:
defmodule Blog.Comment do
use Ecto.Model
schema "comments" do
field :content, :string
belongs_to :post, Blog.Post
end
end
当我生成没有关联的 json 时,结果是这样的:
[%Blog.Post{body: "this is the very first post ever!", id: 1,title: "first post"},
%Blog.Post{body: "Hello nimrod!!!!", id: 12, title: "hi Nimrod"},
%Blog.Post{body: "editing the body!!!!", id: 6, title: "hello(edit)"}]
json 看起来像这样
{"posts": [
{
"title": "first post",
"id": 1,
"body": "this is the very first post ever!"
},
{
"title": "hi Nimrod",
"id": 12,
"body": "Hello nimrod!!!!"
},
{
"title": "hello(edit)",
"id": 6,
"body": "editing the body!!!!"
}
]}
但是有了关联,结果是这样的
[%Blog.Post{body: "this is the very first post ever!",
comments: {Ecto.Associations.HasMany.Proxy,
#Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 1,
title: "first post"},
%Blog.Post{body: "Hello nimrod!!!!",
comments: {Ecto.Associations.HasMany.Proxy,
#Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 12,
title: "hi Nimrod"},
%Blog.Post{body: "editing the body!!!!",
comments: {Ecto.Associations.HasMany.Proxy,
#Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 6,
title: "hello(edit)"}]
使用上述输出,我无法创建正确的 json 输出。我希望 json 看起来像这样
{"posts": [
{
"title": "the title",
"id": 1,
"body": "the body",
"comments": [{"content": "a comment"}, {"content": "another comment"}]
}
...
]}
任何帮助将不胜感激。
【问题讨论】:
-
您使用哪个库来生成 JSON?请添加示例 sn-p。
-
它是默认的phoenix库,毒药:
Poison.encode! %{posts: Blog.Repo.all(Blog.Post)} -
我假设你得到一个错误,对吗?你能把错误贴在这里吗?
-
我的错误信息如下所示:
** (Poison.EncodeError) unable to encode value: {Ecto.Associations.HasMany.Proxy, #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post, associated: Blog.Comment, references: :id, foreign_key: :post_id]>}
标签: json elixir phoenix-framework ecto