首页 > 解决方案 > 使用 Repo.preload 后仍然得到 Ecto.Association.NotLoaded

问题描述

即使在使用 Repo.preload() 预加载后,我仍然会收到 Ecto.Association.NotLoaded。我有一个 has_many :books 的商店模式,当我尝试添加创建商店时,我收到此错误:

%App.Stores.Store{__meta__: #Ecto.Schema.Metadata<:loaded, "stores">, 
name: "mystore", description: "book store", id: 13, inserted_at: 
N[2018-10-10 16:52:24.155385], name: "mystore", books: 
#Ecto.Association.NotLoaded<association :books is not loaded>, 
updated_at: ~N[2018-10-10 16:52:24.155397]}

我研究并发现我的 :books 关联没有加载,所以我将它添加到我的商店上下文中

def list_stores do
    Repo.all(Store)
    Repo.preload(:books)
end

但仍然得到同样的错误。

请这是我的架构

 schema "stores" do
    field :description, :string
    field :name, :string
    has_many :books, Myapp.Books.Book
    field :owner, :string

 timestamps()
end

 @doc false
 def changeset(store, attrs) do
    market
    |> cast(attrs, [:name, :description, :owner])
    |> validate_required([:name, :owner ])
end

 schema "books" do
    field :title, :string
    field :author, :string
    belongs_to :store_id, Myapp.Stores.Store

    timestamps()
  end

  @doc false
  def changeset(pair, attrs) do
    pair
    |> cast(attrs, [:name, :description])
    |> validate_required([:name, :description])
  end

最后是我的迁移文件

def change do
    create table(:books) do
      add :title, :string
      add :name, :string
      add :store_id, references(:stores, on_delete: :nothing)

      timestamps()
    end

    create index(:books, [:store_id])
  end
end

拜托,我不明白,我是 elixir 的新手,并且由于预加载不起作用,我已经研究了其他解决方案。看来我在代码中的某个地方搞砸了,请问我哪里弄错了?

谢谢。

标签: elixirphoenix-framework

解决方案


我终于弄明白了,这是我的 StoreView。我从架构中删除了 store.title 并且仍在视图上调用它。我现在可以添加新书和商店。不敢相信这个小东西让我长久,感谢你们所有的贡献。非常感谢!

太感谢了。


推荐阅读