defmodule Ami.Section do use Ecto.Schema import Ecto.{ Query } alias Ami.{ Repo, # Toolkit, # Tool, SectionTool } schema "sections" do field(:name, :string) field(:position, :integer) field(:sectionable_id, :integer) field(:sectionable_type, :string) has_many(:section_tools, SectionTool) has_many(:section_tools_tools, through: [:section_tools, :tool]) end def preload_sections(struct, sectionable_type) do query = from( s in __MODULE__, where: s.sectionable_type == ^sectionable_type, order_by: s.position ) struct |> Repo.preload( sections: { query, [ [ section_tools: {from(st in SectionTool, order_by: st.tool_position), [:tool]} ], :section_tools_tools ] } ) end end