Last active
February 5, 2019 07:50
-
-
Save turboza/b85f1b5ed339763d2cfd050b6460b549 to your computer and use it in GitHub Desktop.
A confusing moment for Ecto when the data in the database is not updated when doing `Repo.update()`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Experiment do | |
alias SampleApp.{Repo, Order} | |
def run do | |
order = Repo.get(Order, 123) | |
order.status # => "new" | |
# Put status as "pending" while doing some action | |
{:ok, _} = | |
order | |
|> Order.changeset(%{status: "pending"}) | |
|> Repo.update() | |
# revert to original status on failure | |
{:ok, _} = | |
order | |
|> Order.changeset(%{status: order.status}) | |
|> Repo.update() | |
latest_order = Repo.get(Order, 123) | |
latest_order.status # => "pending" ??????? Why not "new"? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Root cause
Ecto will only send
changes
insideChangeset
for database action. Which in this case, there is no change in the second update. So no database update on the secondRepo.update()
Solution
Always use the latest data to send to Ecto Changeset for updating
Thanks to info from the issue: elixir-ecto/ecto#1798