Ecto Association

Hello Good people, i have two models user.ex and profile.ex which have a has_one and belongs_to association respectively.
Below is my code

user.ex

defmodule MyApp.User do
use MyApp.Web, :model

schema “users” do
field :username, :string
field :email, :string
field :user_role, :string
field :password, :string, virtual: true
field :password_hash, :string
field :suspend, :boolean, default: false

has_one :profile, MyApp.Profile

timestamps()
end

profile.ex

defmodule MyApp.Profile do
use MyApp.Web, :model
use Arc.Ecto.Schema

schema “profiles” do
field :firstname, :string
field :lastname, :string
field :avatar, MyApp.Avatar.Type
field :status, :boolean, default: false
belongs_to :user, MyApp.User, foreign_key: :user_id

timestamps()
end

and in my profile controller create function i have this code

def create(conn, %{“profile” => profile_params}) do

changeset =
conn.assigns.current_user
|> build_assoc(:profile)
|> Profile.changeset(profile_params)
|> Repo.preload(:user)
case Repo.insert(changeset) do
  {:ok, profile} ->
    conn
    |> put_flash(:info, "Profile created successfully.")
    |> redirect(to: profile_path(conn, :show, profile))
  {:error, changeset} ->
    render(conn, "new.html", changeset: changeset)
end

end

and lastly in my app.html.eex am trying to render the user’s avatar with this

<%= if @current_user do %>


  • <%= @current_user.profile.avatar %>


  • <%= link “Sign out”, to: session_path(@conn, :delete,
    @current_user), method: “delete” %>

  • <% else %>
  • <%= link “Register”, to: user_path(@conn, :new) %>

  • <%= link “Sign in”, to: session_path(@conn, :new) %>

  • <% end %>

    I get this error after running my server key :avatar not found in: #Ecto.Association.NotLoaded

    i have not been able to figure out where av gone wrong

    1 Like

    You are not loading the Profile association into your User struct.
    Remember that Ecto never does eager loading and you have to explicitly load all associations you want to have available.

    There is a good guide on how to handle associations in Ecto in the Ecto documentation:

    https://hexdocs.pm/ecto/associations.html

    There is also a nice blog post by @josevalim on how to handle associations in Ecto. This should make things clearer if you find the docs hard to read:

    3 Likes