Ecto association with custom name

Suppose I have two schemas, Property, and User.

schema "property" do
  belongs_to :owner, User, [foreign_key: :owner_id]
end

schema "user" do
  has_many :property, Property, [references: :owner_id]
end

And migrations

create table(:user) do
end

create table(:property) do
  add :owner_id, references(:user)
end

When I recompile at the repl, I get

== Compilation error in file lib/app/accounts/user.ex ==
** (ArgumentError) schema does not have the field :owner_id used by association :property, please set the :references option accordingly

I think for your user schema want to set the foreign_key to owner_id, as that is the key it is references on the other schema. by default it will look for user_id on the property schema

You don’t need to set the :references option since the foreign key is still pointing to the id column on the user table

schema "user" do
  has_many :property, Property, foreign_key: :owner_id
end
4 Likes

Thank you! That worked

1 Like