I have this piece of code which increments some serial like value called book_code_serial
.
institute = Repo.one(from i in Mango.Institutes.Institute, where: i.id == 1)
changeset = Mango.Institutes.Institute.book_code_serial_changeset(institute, %{book_code_serial: institute.book_code_serial + 1})
Repo.update!(changeset)
Works fine, but I want to know how this can be rewritten using the ‘|>’ operator, specifically how to do %{book_code_serial: institute.book_code_serial + 1}
inside the pipe. Thank you.
Are you sure you should?
What if institute == nil
, which is a valid return value from Repo.one
?
case Repo.one(...) do
nil ->
...
institute ->
changeset = ...
Repo.update!(changeset)
end
It would just be:
from(i in Mango.Institutes.Institute, where: i.id == 1)
|> Repo.one()
|> (&Mango.Institutes.Institute.book_code_serial_changeset(&1, %{book_code_serial: &1.book_code_serial + 1})).()
|> Repo.update!()
Or:
from(i in Mango.Institutes.Institute, where: i.id == 1)
|> Repo.one()
|> case do in -> Mango.Institutes.Institute.book_code_serial_changeset(in, %{book_code_serial: in.book_code_serial + 1}) end
|> Repo.update!()
Or a few other things you can do, or just make a specialized function for that call as it looks pattern’y. 
1 Like
Thank you very much. Similarly it can be done using:
Repo.one(from i in Mango.Institutes.Institute, where: i.id == 1) |>
(fn institute -> Mango.Institutes.Institute.book_code_serial_changeset(institute, %{book_code_serial: institute.book_code_serial + 1}) end).() |>
Repo.update!()
1 Like
Use a named function instead of an anonymous one. It will be much easier to read.
2 Likes