Search code examples
elixirphoenix-framework

key :xxx not found in: #Ecto.Association.NotLoaded<association :xxx is not loaded> in Phoenix Framework


I generated two models Prefecture and Shop. Shop belongs to Prefecture.

I get errors:

key :prefecture_name not found in:
# Ecto.Association.NotLoaded<association :prefecture is not loaded>

I wrote following code.

Prefecture.ex

defmodule Sample.Prefecture do
  use Ecto.Schema
  import Ecto.Changeset

  schema "prefectures" do
    field :prefecture_name, :string

    has_many :shop, Sample.Shop

    timestamps()
  end

  @doc false
  def changeset(prefecture, attrs) do
    prefecture
    |> cast(attrs, [:prefecture_name])
    |> validate_required([:prefecture_name])
  end
end

Shop.ex

defmodule Sample.Shop do
  use Ecto.Schema
  import Ecto.Changeset

  schema "shops" do
    field :address, :string
    field :phone_no, :string
    field :store_name, :string
    belongs_to :prefecture, Sample.Prefecture

    timestamps()
  end

  @doc false
  def changeset(shop, attrs) do
    shop
    |> cast(attrs, [:store_name, :address, :phone_no, :prefecture_id])
    |> validate_required([:store_name, :address, :phone_no])
  end
end

It seems to be OK. But the error is happened.

key :prefecture_name not found in: #Ecto.Association.NotLoaded<association :prefecture is not loaded>

What I want to make is to get prefecture_name.

What do I need for this code?


Solution

  • In this case, I should have written following.

       Repo.all(Shop) |> Repo.preload(:prefecture)
    

    Thanks.