I have a parent entity and children. The parent entity has a subject_type field - it is responsible for which table the child entity is from, that is, this field stores the name of the child table. That is, child entities can be from different tables. I want to get a list of parent entities with loaded child entities in one request. How can this be implemented?
defmodule MyApp.Parent do
use Ecto.Schema
import Ecto.Changeset
schema "parents" do
field :name, :string
field :subject_type, :string
field :subject_id, :integer
timestamps()
end
def changeset(parent, attrs) do
parent
|> cast(attrs, [:name, :subject_type, :subject_id])
|> validate_required([:name, :subject_type, :subject_id])
end
end
defmodule MyApp.ChildType1 do
use Ecto.Schema
import Ecto.Changeset
schema "child_type1" do
field :description, :string
timestamps()
end
def changeset(child, attrs) do
child
|> cast(attrs, [:description])
|> validate_required([:description])
end
end
defmodule MyApp.ChildType2 do
use Ecto.Schema
import Ecto.Changeset
schema "child_type2" do
field :details, :string
timestamps()
end
def changeset(child, attrs) do
child
|> cast(attrs, [:details])
|> validate_required([:details])
end
end