使用 Repo.preload 后仍然得到 Ecto.Association.NotLoaded
Still getting Ecto.Association.NotLoaded after using Repo.preload
即使在使用 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 的新手并且已经研究了其他解决方案,因为预加载不起作用。看来我在代码的某个地方搞砸了,请问我在哪里弄错了?
谢谢。
终于想通了,原来是我的StoreView。我从架构中删除了 store.title 并且仍在视图上调用它。我现在可以添加新书和商店。不敢相信这件小事让我坚持了这么久,感谢大家的贡献。非常感谢!
非常感谢。
即使在使用 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 的新手并且已经研究了其他解决方案,因为预加载不起作用。看来我在代码的某个地方搞砸了,请问我在哪里弄错了?
谢谢。
终于想通了,原来是我的StoreView。我从架构中删除了 store.title 并且仍在视图上调用它。我现在可以添加新书和商店。不敢相信这件小事让我坚持了这么久,感谢大家的贡献。非常感谢!
非常感谢。