Sto tentando di restituire alcuni dati JSON in una delle mie chiamate API in Phoenix. Sto recuperando tutti i record di Subject
e inviandoli ma Ecto
restituisce alcuni campi aggiuntivi che non desidero.Ottenere solo campi specifici durante il recupero dei dati utilizzando Ecto in Phoenix
Che cosa posso fare per:
- ottenere solo attributi specifici (ad esempio, solo
id
ename
) - Non prelevare i campi non necessari nella mia risposta (come
__meta__
e__owner__
)
Questo è il mio Controller
:
# Controller
def index(conn, _) do
subjects = Subject |> Repo.all
conn |> render subjects: subjects
end
Questo è il mio View
:
# View
def render("index.json", %{subjects: subjects}) do
subjects
end
Questa è la mia risposta:
[
{
"teachers": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "teachers",
"__cardinality__": "many"
},
"updated_at": "2015-06-20T15:32:20Z",
"topics": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "topics",
"__cardinality__": "many"
},
"name": "Physics",
"inserted_at": "2015-06-20T15:32:20Z",
"id": 1,
"__meta__": {
"state": "loaded",
"source": "subjects"
}
},
{
"teachers": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "teachers",
"__cardinality__": "many"
},
"updated_at": "2015-06-20T15:37:59Z",
"topics": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "topics",
"__cardinality__": "many"
},
"name": "Chemistry",
"inserted_at": "2015-06-20T15:37:59Z",
"id": 2,
"__meta__": {
"state": "loaded",
"source": "subjects"
}
},
{
"teachers": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "teachers",
"__cardinality__": "many"
},
"updated_at": "2015-06-20T15:38:41Z",
"topics": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "topics",
"__cardinality__": "many"
},
"name": "Mathematics",
"inserted_at": "2015-06-20T15:38:41Z",
"id": 3,
"__meta__": {
"state": "loaded",
"source": "subjects"
}
},
{
"teachers": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "teachers",
"__cardinality__": "many"
},
"updated_at": "2015-06-22T15:40:17Z",
"topics": {
"__owner__": "Elixir.MyApp.Subject",
"__field__": "topics",
"__cardinality__": "many"
},
"name": "Biology",
"inserted_at": "2015-06-22T15:40:17Z",
"id": 4,
"__meta__": {
"state": "loaded",
"source": "subjects"
}
}
]
Grazie per la risposta. Capisco come selezionare campi specifici, ma cosa succede se voglio rifiutare un campo specifico e ottenere tutto il resto. Ad esempio, se non desidero 'teachers' e' topics' nell'esempio sopra. – Sheharyar
Cambia 'Map.take/2' in' Map.drop/2'. Puoi trovare tutte le funzioni della mappa su http://elixir-lang.org/docs/stable/elixir/. –