Using has_one without using a belongs_to in the other schema


I am learning Ecto and currently, I am struggling with the has_one association. In the Ecto.Schema documentation is stated:

The other schema often has a belongs_to field with the reverse association.

Since it says “often” and not “always”, I was assuming that I could create a schema with a has_one association to another table and leave the other table without a reverse association, because at the moment I don’t need it.

But my assumptions seem to be wrong or I am doing something wrong.

When I try to run the migration with the association, for example:


I get the following error:

deps/ecto/lib/ecto/association.ex:765: field `person_id` in `where` does not exist in schema MyRepo.Address in query:

from a0 in MyRepo.Address,
  where: a0.person_id == ^"437c1381-2a12-222c-804d-d18f2d11ba40",
  select: {a0.person_id, a0}

At this point, I don’t want to add a belongs_to association to Person because I wanted to extend this to have different schemas associations:


And I really did not want to get now into Polymorphic associations which to me is an advanced topic.

In summary, is it possible to use only has_one without the counterpart belongs_to?

Thanks in advance! :smiley:

It’s possible, but you still need to tell Ecto that the column exists (person_id in the Address schema in your example). belongs_to calls field internally, so without it you’ll need to do it yourself.

1 Like

Thank you, now I understand. Appreciate your quick response.