With the help and code samples from friends here (@idi527 and others) I have written this function to create multiple book
related records. I pass to this function some shared data (current_user
and borrower_id
) along with a comma separated list of book_ids
. I make some custom validations, insert if everything is fine or return error messages if something is wrong. What I receive back at the client side is the result
list (as JSON):
def create_record(%{"user_object" => user, "borrower_id" => borrower_id} = attrs, book_list) do
book_list = String.split(book_list, ",")
result = []
for book_id <- book_list do
book_id = book_id |> String.to_integer
alias Ecto.Multi
record_changeset = Mango.Records.Record.changeset(%Record{user_id: user.id, book_id: book_id}, attrs)
Multi.new()
|> Mango.Records.Validators.valid_book_exists_multi(book_id)
|> Mango.Records.Validators.valid_book_belongs_to_current_user_and_borrower_multi(book_id, user, borrower_id)
|> Mango.Records.Validators.valid_last_record_closed_multi(book_id)
|> Multi.insert(:record, record_changeset)
|> Repo.transaction()
|> case do
{:ok, :first_record} -> {:ok}
{:ok, %{record: record}} -> result = result ++ record
{:error, :book_belongs_to_current_user_and_borrower, reason, _changes} -> result = result ++ reason
{:error, :book_exists, reason, _changes} -> result = result ++ reason
{:error, :last_record_closed, reason, _changes} -> result = result ++ reason
end
end
end
You’re welcome to review it and provide feedback