Current section

Files

Jump to
ami lib ami comment.ex
Raw

lib/ami/comment.ex

defmodule Ami.Comment do
use Ecto.Schema
import Ecto.{
Query,
Changeset
}
alias Ami.{
# Post,
User,
Like,
Resource,
CommentAttachment,
Repo
}
schema "comments" do
@timestamps_opts [type: :naive_datetime_usec]
field(:body, :string)
field(:commentable_type, :string)
field(:commentable_id, :integer)
field(:is_inappropriate, :boolean, default: false)
field(:created_at, :utc_datetime_usec)
field(:updated_at, :utc_datetime_usec)
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