Need help with Ecto associations

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.

belongs_to calls field internally for the column it uses, you don’t need the first line here.

Be careful with editing migrations - it’s fine when you’re starting out a project and can drop & recreate the database, but it’s not something you’d want to do in an application that cares about the data.

3 Likes