Ecto.Schema.has_one

You're seeing just the macro has_one, go back to Ecto.Schema module for more information.
Link to this macro

has_one(name, queryable, opts \\ [])

View Source (macro)

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 in has_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, set references(:parent_id, on_delete: :delete_all). Opposite to the migration option, this option cannot guarantee integrity and it is only triggered for Ecto.Repo.delete/2 (and not on Ecto.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 using Ecto.Multi or Ecto.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. See Ecto.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 set Post.has_one :banner, defaults: [public: true], then when using Ecto.build_assoc(post, :banner), the banner will have banner.public == true. Alternatively, you can set it to Post.has_one :banner, defaults: :update_banner, which will invoke Post.update_banner(banner, post), or set it to a MFA tuple such as {Mod, fun, [arg3, arg4]}, which will invoke Mod.fun(banner, post, arg3, arg4)

  • :where - A filter for the association. See "Filtering associations" in has_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{...}