Relations
Has_many
One to One
belongs_to
indicates a one-to-one or many-to-one association with another schema. Defines a foreign key that is the primary key of the listed table.
belongs_to
(has the id in its table) =>has_one
has their id in their belongs_to tableThe other schema often has a
has_one
or ahas_many
field with same fields, but reverse association. (Both the has macros don't change DB, just allow access)
Usage
Updating from parent
You could pass in %{id: 1, child: [1]}
:on_replace
- The action taken on associations when the record is replaced when casting or manipulating parent changeset. May be:raise
(default),:mark_as_invalid
,:nilify
,:update
, or:delete
. SeeEcto.Changeset
's section on related data for more info.
Create/Update Relations
This function should be used when working with the entire association at once (and not a single element of a many-style association) and receiving data external to the application.
It compares each of param to preloaded
No id or id not in db => insert
if id and in db => update
If no id, but id in db => delete/on_replace
In Creation
In Update
In Get
Example Schema
Last updated