Ecto - 使用父关联创建记录时预加载关联

时间:2017-02-21 19:22:48

标签: elixir phoenix-framework ecto

在传递1到多个关联的父记录的ID值时,在创建子记录时,我在关联上收到错误。

错误说我需要将User作为父记录预加载到Transaction

  1) test creates and renders resource when data is valid (MyRewardsWeb.TransactionControllerTest)
       test/controllers/transaction_controller_test.exs:36
       ** (RuntimeError) attempting to cast or change association `user` from `MyRewards.Transaction` that was not loaded. Please preload your associations before manipulating them thr
  ough changesets
       stacktrace:
         (ecto) lib/ecto/changeset/relation.ex:66: Ecto.Changeset.Relation.load!/2
         (ecto) lib/ecto/repo/schema.ex:514: anonymous fn/4 in Ecto.Repo.Schema.surface_changes/4

         (elixir) lib/enum.ex:1623: Enum."-reduce/3-lists^foldl/2-0-"/3
         (ecto) lib/ecto/repo/schema.ex:503: Ecto.Repo.Schema.surface_changes/4
         (ecto) lib/ecto/repo/schema.ex:186: Ecto.Repo.Schema.do_insert/4
         (my_rewards_web) web/controllers/transaction_controller.ex:20: MyRewardsWeb.TransactionController.create/2
         (my_rewards_web) web/controllers/transaction_controller.ex:1: MyRewardsWeb.TransactionController.action/2
         (my_rewards_web) web/controllers/transaction_controller.ex:1: MyRewardsWeb.TransactionController.phoenix_controller_pipeline/2
         (my_rewards_web) lib/my_rewards_web/endpoint.ex:1: MyRewardsWeb.Endpoint.instrument/4
         (my_rewards_web) lib/phoenix/router.ex:261: MyRewardsWeb.Router.dispatch/2
         (my_rewards_web) web/router.ex:1: MyRewardsWeb.Router.do_call/2
         (my_rewards_web) lib/my_rewards_web/endpoint.ex:1: MyRewardsWeb.Endpoint.phoenix_pipeline/1
         (my_rewards_web) lib/my_rewards_web/endpoint.ex:1: MyRewardsWeb.Endpoint.call/2
         (phoenix) lib/phoenix/test/conn_test.ex:224: Phoenix.ConnTest.dispatch/5
         test/controllers/transaction_controller_test.exs:41: (test)

在我的控制器方法中,我发现UserMerchant记录都是Transaction结构的父记录,并在创建变更集时传递相应的记录ID

  def create(conn, %{"merchant_id" => merchant_id, "mobile" => mobile, "amount" => amount}) do
    customer = MyRewards.find_user!(%{"mobile" => mobile})
    merchant = Repo.get(MyRewards.Merchant, merchant_id)
    changeset = MyRewards.create_deposit_changeset(%{"user_id" => customer.id, "merchant_id" => merchant.id, "amount" => amount })
    case Repo.insert(changeset) do
      {:ok, transaction} ->
        conn
        |> put_status(:created)
        |> put_resp_header("location", transaction_path(conn, :show, transaction))
        |> render("show.json", transaction: transaction)
      {:error, changeset} ->
        conn
        |> put_status(:unprocessable_entity)
        |> render(MyRewardsWeb.ChangesetView, "error.json", changeset: changeset)
    end
  end

此函数只传递信息并返回变更集:

 def create_deposit_changeset(user_id: user_id, merchant_id: merchant_id, amount: amount) do
   MyRewards.Transaction.deposit(%MyRewards.Transaction{}, %{ merchant_id: merchant_id, user_id: user_id, amount: Money.new(amount) })
 end

在结构中,我定义了关系,并将user_idmerchant_id正确地转换为Transaction Ecto Struct定义中的参数。

defmodule MyRewards.Transaction do

  @entry_types [:credit, :debit]

  use MyRewards.Model
  schema "my_rewards_transactions" do
    field :amount, Money.Ecto.Type
    field :type, :string
    belongs_to :user, MyRewards.User
    belongs_to :merchant, MyRewards.Merchant

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:amount, :type, :user_id, :merchant_id])
    |> validate_required([:amount, :type])
  end

  def deposit(struct, params) do
    struct
    |> cast( %{type:  "debit"}, [:type])
    |> changeset(params)
  end


  def widthdraw(struct, params) do
    struct
    |> cast( %{type: "credit"}, [:type])
    |> changeset(params)
  end
end

当我在测试用例中测试该函数时,它输入的事务正常。

MyRewards.create_deposit_changeset(user_id: customer.id, merchant_id: merchant.id, amount: x) 

但是当我在凤凰控制器中运行它时,它失败了。我不确定它为什么会失败或要求预加载父协会。我应该在某处put_assoc而不是直接将user_idmerchant_id作为参数投放吗?

1 个答案:

答案 0 :(得分:2)

问题是我作为OTP应用程序的设置无法共享Ecto的预加载方面。我在凤凰城的网站很好,但我无法在控制器中提交变更集,因为Phoenix应用程序中的Repo与变更集是OTP应用程序的引用不同,这导致了预加载错误。

我提取它的原因是由于!我错过了原始设置。

我将控制器改回原来这样,它返回{:ok, transaction},就像这样

case MyRewards.create_deposit(%{"user_id" => customer.id, "merchant_id" => merchant.id, "amount" => amount }) do
  {:ok, transaction} ->
    conn
    |> put_status(:created)
    |> put_resp_header("location", transaction_path(conn, :show, transaction))
    |> render("show.json", transaction: transaction)
  {:error, changeset} ->
    conn
    |> put_status(:unprocessable_entity)
    |> render(MyRewardsWeb.ChangesetView, "error.json", changeset: changeset)
end

这是不同的,因为我没有返回变更集。我正在OTP应用程序中执行Repo.insert并返回事务。

def create_deposit(%{"user_id" => user_id, "merchant_id" => merchant_id, "amount" => amount }) do
  MyRewards.Transaction.deposit(%MyRewards.Transaction{}, %{ merchant_id: merchant_id, user_id: user_id, amount: Money.new(amount) })
    |> MyRewards.Repo.insert
end

我之所以改变的原因是因为我使用的是|> MyRewards.Repo.insert!而不是|> MyRewards.Repo.insert ....最后!爆炸将函数的返回更改为只返回结构而不是返回状态和像{:ok, transaction}这样的结构,这是控制器所期望的。

简而言之,如果您将应用程序拆分为OTP和Phoenix,请注意repo插入中的!