【发布时间】:2017-02-24 02:12:35
【问题描述】:
我正在开发一个 Phoenix 应用程序,它是 Evernote 的个人版本。我有一个Book 模型,那个has_many Note 记录。
这是我的图书模型:
defmodule Notebook.Book do
use Notebook.Web, :model
schema "books" do
field :name, :string, default: ""
has_many :notes, Notebook.Note
belongs_to :user, Notebook.User
timestamps()
end
@doc """
Book changeset. Name field required.
"""
def changeset(model, params \\ %{}) do
model
|> cast(params, [:name])
|> validate_required(:name)
end
end
我的控制器中有一个更新端点:
def update(conn, %{"id" => id, "book" => book_params}) do
existing_book = Repo.get(Book, id)
changeset = Book.changeset(existing_book, book_params)
case Repo.insert(changeset) do
{:ok, book} ->
conn
|> put_status(:ok)
|> render("show.json", book: book)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render("error.json", message: changeset.errors)
end
end
还有一个测试:
test "with a valid jwt", %{conn: conn, jwt: jwt} do
book = insert(:book)
resp = conn
|> put_req_header("authorization", "Bearer: #{jwt}")
|> put(book_path(Endpoint, :update, book, book: %{name: "New Book"}))
|> json_response(:ok)
assert resp["data"]["book"]["name"] == "New Book"
end
当我运行我的测试时,我得到了这个错误:
** (RuntimeError) attempting to cast or change association `notes` from `Notebook.Book` that was not loaded. Please preload your associations before manipulating them through changesets
我发送的参数只有name。调查了一下,我找到了related issue,但由于我没有使用cast_assoc,我认为它不适用。
我无法弄清楚我在这里做错了什么。我了解(我认为)在 Ecto 中预加载关系,但在这种情况下,我不会更新依赖的 Note 记录,只是 Book 记录的一个字段,所以我不需要预加载。
整个仓库是here。
【问题讨论】:
标签: elixir phoenix-framework ecto