我确实有这个控制器和模板视图,我在POST到创建操作时收到此错误:
我是否特别想设置一些插件?
** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection
Elixir 1.3.2 凤凰城1.2.1 毒药3.0
控制器中的部分代码
def create(conn, %{"cart" => cart, "form" => form}) do
...
if changeset_order.valid? do
Repo.transaction fn ->
# Save Order
order = changeset_order
|> Repo.insert!
|> Repo.preload(:buyer)
# Save Order Products
Enum.map(order_products, fn order_product ->
order_product = Repo.insert!(order_product) |> Repo.preload(:order)
changeset = Ecto.Changeset.change(order_product) |> Ecto.Changeset.put_assoc(:order, order)
Repo.update!(changeset)
end)
CheckoutService.charge_customer(total_amount, "fake-valid-nonce")
render conn, "show.json", order: order <--- Is this failing due to is called from within a transaction ?
end
else
render conn, ExRushlookApi.ChangesetView, "error.json", changeset: changeset_order
end
模板视图
defmodule ExRushlookApi.OrderView do
use ExRushlookApi.Web, :view
def render("index.json", %{orders: orders}) do
%{data: render_many(orders, __MODULE__, "order.json")}
end
def render("show.json", %{order: order}) do
%{data: render_one(order, __MODULE__, "order.json")}
end
def render("order.json", %{order: order}) do
order |> IO.inspect
%{id: Map.get(order, :id)}
end
def render("errors.json", %{errors: errors}) do
%{errors: render_many(errors, __MODULE__, "error.json")}
end
def render("error.json", %{error: error}) do
%{
key: error.key,
value: error.value
}
end
end
更新:它以这种方式工作。
if changeset_order.valid? do
{:ok, order } = Repo.transaction fn ->
# Save Order
order = changeset_order
|> Repo.insert!
|> Repo.preload(:buyer)
# Save Order Products
Enum.map(order_products, fn order_product ->
order_product = Repo.insert!(order_product) |> Repo.preload(:order)
changeset = Ecto.Changeset.change(order_product) |> Ecto.Changeset.put_assoc(:order, order)
Repo.update!(changeset)
end)
CheckoutService.charge_customer(total_amount, "fake-valid-nonce")
order
end
conn
|> render("show.json", order: order)
else
conn
|> render(ExRushlookApi.ChangesetView, "error.json", changeset: changeset_order)
end
答案 0 :(得分:4)
您的交易区内有render conn, "show.json", ...
次来电。它应该在阻止之后。事务块返回事务的结果,而不是最后一个语句。
如果您只想在成功时渲染节目,您应该检查交易结果并在那里处理。