It could also be failing on your .get_zzz!s but if itâs that, when corrected it would still fail when you use fn %{book: book} as you need to use a key that refers to a previous multi âstepâ I guess - I just recently started using multi though
Update is a different kind of call, it is better to use though, but still, run requires {:ok, result}/{:error, reason} and I bet that one of those were not.
When I set the run methods to return {:ok, result} it did not work because in the next line I was getting error like: could not find key record_id in :ok.record_id or something like that, but when I set the run method to return result only it worked. Like this:
def update_book_to_be_returned_multi(multi, book_id) do
alias Ecto.Multi
alias Mango.Books
alias Mango.Books.Book
Multi.run(multi, :book_to_be_returned, fn _changes ->
case Repo.get_by(Book, %{id: book_id, status: :out}) do
nil ->
{:error, %{error: "Book not found or already available.."}}
book ->
case Books.update_book(book, %{status: :available}) do
book = book -> book
nil -> {:error, %{error: "Error occured while updating the book.."}}
end
end
end)
end
I grepped for Multi.runâs at work and although I have a number of them I donât use any of the previous values of the things (simple log dispatches and such)⊠HmmâŠ
def update_book_to_be_returned_multi(book_id) do
alias Mango.Books.Book
case Repo.get_by(Book, %{id: book_id, status: :out}) do
nil ->
{:error, %{error: "Book not found or already available.."}}
book ->
case Books.update_book(book, %{status: :available}) do
book -> {:ok, book}
nil -> {:error, %{error: "Error occured while updating the book.."}}
end
end
end
And:
multi_result =
Multi.new()
|> Multi.run(:book_to_be_returned, update_book_to_be_returned_multi(line.book_id)
|> Multi.run(:update_associated_record, fn %{book_to_be_returned: book_to_be_returned} ->
Records.update_record(Repo.get(Record, book_to_be_returned.record_id), %{
returned_at: :os.system_time(:seconds)
})
end)
def update_book_to_be_returned_multi(book_id) do
alias Mango.Books
alias Mango.Books.Book
case Repo.get_by(Book, %{id: book_id, status: :out}) do
nil ->
{:error, %{error: "Book not found or already available.."}}
book ->
case Books.update_book(book, %{status: :available}) do
{:ok, book} -> {:ok, book} # update_book returns %{:ok, book_object } so this is the correct match
nil -> {:error, %{error: "Error occured while updating the book.."}}
end
end