I have a simple todo / author model where todo has a author_id field.
The models are defined as follows:
defmodule TodoElixir.User.Author do
use Ecto.Schema
import Ecto.Changeset
schema "authors" do
field :email, :string
field :name, :string
field :password, :string, virtual: true
field :hash, :string
has_many :todos, Main.Todo
timestamps()
end
Here I get a
warning: invalid association
todo
in schema TodoElixir.User.Author: associated schema Main.Todo does not exist
And the todo model:
defmodule TodoElixir.Main.Todo do
use Ecto.Schema
import Ecto.Changeset
schema "todos" do
field :date, :date
field :description, :string
field :title, :string
belongs_to :author, User.Author
timestamps()
end
I also have a migration for each:
defmodule TodoElixir.Repo.Migrations.CreateAuthors do
use Ecto.Migration
def change do
create table(:authors) do
add :name, :string
add :email, :string
add :hash, :string
has_many :todos, Main.Todo
timestamps()
end
end
end
defmodule TodoElixir.Repo.Migrations.CreateTodos do
use Ecto.Migration
def change do
create table(:todos) do
add :title, :string
add :description, :string
add :date, :date
add :author_id, references(:authors)
timestamps()
end
end
end
If I remove has_many :todos, Main.Todo
from the module, it compiles and I can query
http://localhost:4000/api/todos but the author field is not set.
I've tried using preload and assoc but following https://elixirschool.com/en/lessons/ecto/associations/ the association should be automatic...
In the todo controller I have:
def index(conn, _params) do
todos = Main.list_todos()
render(conn, "index.json", todos: todos)
end
and list_todos =
def list_todos do
Repo.all(Todo)
end
EDIT:
In the controller I put:
def index(conn, _params) do
todos = Repo.all(Todo) |> Repo.preload(:author)
render(conn, "index.json", todos: todos)
end
I see the query in the console:
[debug] Processing with TodoElixirWeb.TodoController.index/2
Parameters: %{} Pipelines: [:api] [debug] QUERY OK source="todos" db=6.3ms decode=1.7ms queue=0.8ms SELECT t0."id", t0."date", t0."description", t0."title", t0."author_id", t0."inserted_at", t0."updated_at" FROM "todos" AS t0 [] [debug] QUERY OK source="authors" db=0.6ms queue=1.0ms SELECT a0."id", a0."email", a0."name", a0."hash", a0."inserted_at", a0."updated_at", a0."id" FROM "authors" AS a0 WHERE (a0."id" = $1)
Which looks good to me, but the JSON result:
{"data":[{"date":null,"description":"we need to do this","id":1,"title":"My first todo"}]}
Should I tell Elixir to add the associations in the JSON response as well? How?