Vorrei generare JSON da un'associazione ecto in phoenix.creazione json da elixir associazioni ecto
questa è la mia associazione:
defmodule Blog.Post do
use Ecto.Model
schema "posts" do
field :title, :string
field :body, :string
has_many :comments, Blog.Comment
end
end
e:
defmodule Blog.Comment do
use Ecto.Model
schema "comments" do
field :content, :string
belongs_to :post, Blog.Post
end
end
quando ho generare JSON, senza l'associazione Il risultato è questo:
[%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)"}]
e JSON assomiglia a questo
{"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!!!!"
}
]}
ma con l'associazione del risultato è questo
[%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)"}]
Con l'uscita di cui sopra non può creare un'uscita json corretta. Vorrei che Json assomigliasse a qualcosa del genere
{"posts": [
{
"title": "the title",
"id": 1,
"body": "the body",
"comments": [{"content": "a comment"}, {"content": "another comment"}]
}
...
]}
Qualsiasi aiuto sarebbe apprezzato.
Quale libreria si usa per generare il JSON? Si prega di aggiungere uno snippet di esempio. –
È la libreria phoenix predefinita, Poison: 'Poison.encode! % {post: Blog.Repo.all (Blog.Post)} ' – idobn
Suppongo che tu abbia ricevuto un errore, vero? Puoi per favore postare l'errore qui? –