Ecto.Schema `has_one/3` and `belongs_to/3` options (`:foreign_key` and `:references`) confusion
( has_many/3
belongs here too I guess)
Published in
1 min readFeb 8, 2019
Being bad at reading comprehension, the official docs were little to no help:
From Ecto.Schema.belongs_to/3
:
:foreign_key -
Sets the foreign key field name, defaults to the
name of the association suffixed by _id. For
example, belongs_to :company will define foreign key
of :company_id:references -
Sets the key on the other schema to be used for the
association, defaults to: :id:type -
Sets the type of automatically defined
:foreign_key. Defaults to: :integer and can be set
per schema via @foreign_key_type
… and from Ecto.Schema.has_one/3
(and has_many/3
):
:foreign_key -
Sets the foreign key, this should map to a field on
the other schema, defaults to the underscored name
of the current module suffixed by _id:references -
Sets the key on the current schema to be used for
the association, defaults to the primary key on the
schema
Examples from working code:
(Today’s soundtrack was “Hammer To Fall” from QUEEN. All day.)