elixir - 使用 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 的新手,并且由于预加载不起作用,我已经研究了其他解决方案。看来我在代码中的某个地方搞砸了,请问我哪里弄错了?
谢谢。
解决方案
我终于弄明白了,这是我的 StoreView。我从架构中删除了 store.title 并且仍在视图上调用它。我现在可以添加新书和商店。不敢相信这个小东西让我长久,感谢你们所有的贡献。非常感谢!
太感谢了。
推荐阅读
- sql - 枢轴并获得排名
- ruby-on-rails - 在你的命令前加上 `bundle exec` 可以解决这个问题。甚至预先捆绑执行
- python - 返回空的函数支持清除临时数据
- xpath - 如何使用 Scrapy XPATH 选择这个元素?
- amazon-web-services - Certbot 无法找到环境变量凭据
- java - java虚拟机启动器错误:发生jni错误
- javascript - 当字符串为空时,如何防止 EventListener “keyup”对“backspace”做出反应?
- assembly - 恒定的非不变 tsc 可以跨 cpu 状态改变频率吗?
- puppet - 我可以省略 site.pp 在所有节点上执行一个类吗
- javascript - 遍历范围[]