I am trying to select a specific lesson from a table and load its associated exercises in a template with something like:
these are the schemas:
schema "lessons" do
field :lesson_id, :string
field :url, :string
field :title, :string
field :description, :string
has_many :exercises, Swish.Exercise
schema "exercises" do
field :nativeword, :string
field :foreignword, :string
belongs_to :lessons, Swish.Lesson, foreign_key: :lesson_id
in the IEX i ran this query:
Repo.all from l in Lesson, join: e in assoc(l, :exercises), preload: [exercises: e]
which returned:
QUERY OK source="lessons" db=22.6ms decode=5.6ms
SELECT l0."id", l0."lesson_id", l0."url", l0."title", l0."description", l0."inserted_at", l0."updated_at", e1."id", e1."nativeword", e1."foreignword", e1."lesson_id", e1."inserted_at", e1."updated_at" FROM "lessons" AS l0 INNER JOIN "exercises" AS e1 ON e1."lesson_id" = l0."id" []
[%Swish.Lesson{__meta__: #Ecto.Schema.Metadata<:loaded, "lessons">,
description: "The road to hell is paved with good intentions",
exercises: [%Swish.Exercise{__meta__: #Ecto.Schema.Metadata<:loaded, "exercises">,
foreignword: "Hello", id: 1, inserted_at: ~N[2017-07-23 02:21:47.078325],
lesson: #Ecto.Association.NotLoaded<association :lesson is not loaded>,
lesson_id: 3, nativeword: "hola",
updated_at: ~N[2017-07-23 02:21:47.085057]},
This at first looked alright to me but now i see that lesson association is not correct. I got this error:
protocol Ecto.Queryable not implemented for [%Swish.Lesson{__meta__: #Ecto.Schema.Metadata<:loaded, "lessons">, description: "The road to hell is paved with good intentions", exercises: [%Swish.Exercise{__meta__: #Ecto.Schema.Metadata<:loaded, "exercises">, foreignword: "Hello", id: 1, inserted_at: ~N[2017-07-23 02:21:47.078325], lesson_id: 3, lessons: #Ecto.Association.NotLoaded<association :lessons is not loaded>, nativeword: "hola", updated_at: ~N[2017-07-23 02:21:47.085057]},
when running these functions and queries in a phoenix framework:
plug :load_exercises when action in [:show]
defp load_exercises(conn, _) do
query =
Exercise
|> Lesson.preload_exercises
exercises = Repo.all query
assign(conn, :exercises, exercises)
end
def preload_exercises(query) do
Swish.Repo.all from l in Swish.Lesson, join: e in assoc(l, :exercises), preload: [exercises: e]
end
This is what i used to seed the data:
Repo.insert %Exercise{ nativeword: "hola", foreignword: "Hello", lesson_id: 3}
Repo.insert %Exercise{ nativeword: "adios", foreignword: "goodbye", lesson_id: 3}
Repo.insert %Exercise{ nativeword: "uno", foreignword: "one", lesson_id: 4}
Repo.insert %Exercise{ nativeword: "dos", foreignword: "two", lesson_id: 4}
Is there any way to remedy this? Thanks!