Elixir Ecto:有人可以举个例子 Ecto.Multi.run/5

Elixir Ecto: Could someone give an example of Ecto.Multi.run/5

docs状态

run(t, name, module, function, args) :: t when function: atom, args: [any]

Similar to run/3, but allows to pass module name, function and arguments. The function should return either {:ok, value} or {:error, value}, and will receive changes so far as the first argument (prepened to those passed in the call to the function).

但我不确定如何使用它。假设我有这个功能,我想在 Ecto.Multi:

中 运行
def some_fun(value, other_value) do
  case value do
    nil -> {:error, other_value}
    _ -> {:ok, other_value}
  end
end

那将如何运作?

我假设您希望 value 成为 "changes so far",而 other_value 是您在调用 Multi.run/5 时指定的值。在这种情况下,如果您的函数位于名为 Foo:

的模块中
defmodule Foo do
  def some_fun(value, other_value) do
    case value do
      nil -> {:error, other_value}
      _ -> {:ok, other_value}
    end
  end
end

那么您的 Multi.run/5 电话将是:

Multi.run(multi, name, Foo, :some_fun, [other_value])

相当于以下 Multi.run/3 调用:

Multi.run(multi, name, fn value -> Foo.some_fun(value, other_value) end)