【问题标题】:Phoenix model with has_many relation will not update w/o preloading the relation具有 has_many 关系的 Phoenix 模型不会在没有预加载关系的情况下更新
【发布时间】: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


    【解决方案1】:

    看起来您在BookControllerupdate 方法中使用了Repo.insert。将其更改为 Repo.update 应该可以解决它。

    【讨论】:

    • 谢谢先生!我已经被困了一段时间了。
    猜你喜欢
    • 2021-07-19
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多