defmodule Ami.Comment do use Ecto.Schema import Ecto.{ Query, Changeset } alias Ami.{ # Post, User, Like, Resource, CommentAttachment, Repo } schema "comments" do field(:body, :string) field(:commentable_type, :string) field(:commentable_id, :integer) field(:is_inappropriate, :boolean, default: false) field(:created_at, :utc_datetime) field(:updated_at, :utc_datetime) belongs_to(:user, User) belongs_to(:comment, __MODULE__, foreign_key: :main_comment_id) has_many(:likes, Like, foreign_key: :likeable_id) has_many(:resources, Resource, foreign_key: :resourceable_id) has_many(:subcomments, __MODULE__, foreign_key: :main_comment_id, on_delete: :delete_all) has_many(:comment_attachments, CommentAttachment, on_delete: :delete_all) end def preload_comments(struct, commentable_type) do struct |> Repo.preload( comments: from( c in __MODULE__, where: c.commentable_type == ^commentable_type, order_by: [desc: c.id], preload: [:comment_attachments, subcomments: [:likes, user: :profile]] ) ) end def preload_likes(comment), do: Like.preload_likes(comment, "Comment") def changeset(comment, params \\ %{}) do comment |> cast(params, [ :created_at, :updated_at, :commentable_type, :commentable_id, :user_id, :body ]) |> validate_required([:user_id, :commentable_id, :commentable_type, :body]) end end