Preload trying to get the wrong column name

David Magalhães Source

I have the following objects.

defmodule Ketchup.Review do
  ...

  schema "order_review" do
    ...

    has_many :review_tags, Review.Tag

  end
end

And

defmodule Ketchup.Review.Tag do
  ...
  schema "review_tag" do
    ...
    belongs_to :order_review, Ketchup.Review
  end
end

And using the following query

@preload [:review_tags, :order]
def get_review_by_order(order_id) do
  Ketchup.Review
  |> where([c], c.order_id == ^order_id)
  |> preload(^@preload)
  |> Repo.one()
end

Give the following error:

 ** (Ecto.QueryError) deps/ecto/lib/ecto/association.ex:495: field `Ketchup.Review.Tag.review_id` in `where` does not exist in the schema in query:

 from t in Ketchup.Review.Tag,
   where: t.review_id == ^2,
   order_by: [asc: t.review_id],
   select: {t.review_id, t}

Where is coming this review_id ? I've checked all the code for review and any atom or association, but can't find anything. It should be order_review_id.

The review tag is created with the following migration:

create table(:review_tag) do
  add :review_tag, :string
  add :order_review_id, references(:order_review, on_delete: :delete_all)
end
elixirecto

Answers

answered 3 months ago Justin Wood #1

Ecto is trying to use the key review_id because your module name ends with Review. If you want to use some other key, you will have to specify the :foreign_key option in your has_many/3 call.

has_many :review_tags, Ketchup.Review, foreign_key: :order_review_id

Just note that I am guessing the key name based on the belongs_to/3 you have specified.

comments powered by Disqus