Ecto.Schema.has_one
has_one
, go back to Ecto.Schema module for more information.
Indicates a one-to-one association with another schema.
The current schema has zero or one records of the other schema. The other
schema often has a belongs_to
field with the reverse association.
Options
: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:through
- If this association must be defined in terms of existing associations. Read the section inhas_many/3
for more information:on_delete
- The action taken on associations when parent record is deleted. May be:nothing
(default),:nilify_all
and:delete_all
. Using this option is DISCOURAGED for most relational databases. Instead, in your migration, setreferences(:parent_id, on_delete: :delete_all)
. Opposite to the migration option, this option cannot guarantee integrity and it is only triggered forEcto.Repo.delete/2
(and not onEcto.Repo.delete_all/2
) and it never cascades. If posts has many comments, which has many tags, and you delete a post, only comments will be deleted. If your database does not support references, cascading can be manually implemented by usingEcto.Multi
orEcto.Changeset.prepare_changes/2
: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.:defaults
- Default values to use when building the association. It may be a keyword list of options that override the association schema or as a atom/{module, function, args}
that receives the struct and the owner as arguments. For example, if you setPost.has_one :banner, defaults: [public: true]
, then when usingEcto.build_assoc(post, :banner)
, the banner will havebanner.public == true
. Alternatively, you can set it toPost.has_one :banner, defaults: :update_banner
, which will invokePost.update_banner(banner, post)
, or set it to a MFA tuple such as{Mod, fun, [arg3, arg4]}
, which will invokeMod.fun(banner, post, arg3, arg4)
:where
- A filter for the association. See "Filtering associations" inhas_many/3
. It does not apply to:through
associations.
Examples
defmodule Post do
use Ecto.Schema
schema "posts" do
has_one :permalink, Permalink
# Specify the association with custom source
has_one :category, {"posts_categories", Category}
end
end
# The permalink can come preloaded on the post struct
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :permalink))
post.permalink #=> %Permalink{...}