I read up on Ecto Associations. Here is what I ended up doing. First I added has_many
to my post.ex
schema:
schema "posts" do
field :body, :string
field :title, :string
has_many :comments, BlogApp.Comments.Comment
Next in my comment.ex
schema I put belongs_to
:
schema "comments" do
field :content, :string
field :name, :string
field :post_id, :id
belongs_to :post, BlogApp.Posts.Post
timestamps()
end
In my migration folder I went ahead and edited the create_comments.exs
file toadd :delete_all
:
defmodule BlogApp.Repo.Migrations.CreateComments do
use Ecto.Migration
def change do
create table(:comments) do
add :name, :string
add :content, :text
add :post_id, references(:posts, on_delete: :delete_all)
timestamps()
end
create index(:comments, [:post_id])
end
end
lastly, I did ecto. migrate, I started the server and got this error saying that :post_id is already set on schema, but that post_id was there from the start
== Compilation error in file lib/blog_app/comments/comment.ex ==
** (ArgumentError) field/association :post_id is already set on schema
(ecto 3.7.2) lib/ecto/schema.ex:2146: Ecto.Schema.put_struct_field/3
(ecto 3.7.2) lib/ecto/schema.ex:1899: Ecto.Schema.define_field/4
(ecto 3.7.2) lib/ecto/schema.ex:1986: Ecto.Schema.__belongs_to__/4
lib/blog_app/comments/comment.ex:9: (module)
Do I need to edit the controllers? My goal is to get the comments on the post to delete when I delete the main Blog. Parent child, they should be connected.