defmodule Ami.Toolkit do use Ecto.Schema # import Ecto.{ # Query # } alias Ami.{ Community, User, ToolkitTool, # Tool, Like, Share, Repo, Section } schema "tool_kits" do field(:title, :string) field(:description, :string) field(:available_to_other_community, :boolean) field(:created_at, :utc_datetime) field(:updated_at, :utc_datetime) field(:tools_count, :integer, virtual: true, default: 0) field(:views_count, :integer) belongs_to(:community, Community) belongs_to(:author, User, foreign_key: :user_id) has_many(:toolkit_tools, ToolkitTool, foreign_key: :tool_kit_id) has_many(:tools, through: [:toolkit_tools, :tool]) has_many(:likes, Like, foreign_key: :likeable_id) has_many(:shares, Share, foreign_key: :shareable_id) has_many(:sections, Section, foreign_key: :sectionable_id) end def fetch_tools_count(toolkit) do count = length(Repo.preload(toolkit, :tools).tools) %__MODULE__{toolkit | tools_count: count} end def preload_likes(toolkit), do: Like.preload_likes(toolkit, "ToolKit") def preload_sections(toolkit), do: Section.preload_sections(toolkit, "ToolKit") end