PJUllrich

PJUllrich

Author of Building Table Views with Phoenix LiveView

How to update a Struct without explicit Attributes

Hey folks,

I wondered whether it is possible to update a struct without explicitly defining the attributes that were updated. So, something similar to Ruby where you can update fields on an object and then run:

user = User.find_by(name: 'David')
user.name = 'Dave'
user.save

Let me explain in code what I want to achieve:

# I have a struct that has only one field called "status"
defmodule Order do

  # The struct has a function that updates the status field based on some domain logic
  def refund(%{status: status} = order) when status != :refunded do
    {:ok, Map.merge(order, %{status: :refunded})}
  end
  
  def refund(_order), do: {:error, :order_already_refunded}

  # The struct/Ecto.Schema also has a changeset that does some casting and validating
  # I don't want to have to define which attributes should be updated here though.
  # The changeset (or the context below) should auto-magically find the fields that changed
  # OR simply update all fields except associations. This would work too because then
  # I'd simply overwrite all fields that didn't change with their current value.
  def changeset(order) do
    attrs = somehow_get_attrs_without_knowing_which_fields_changed(order)

    order
    |> cast(attrs, [:status])
    |> validate_required([:status])
  end
end

defmodule Orders do
  # I have a context with an update function that only uses the struct
  # This is different from the usual "update_order(order, attrs)" function.
  def update_order(order) do
    order
    |> Order.changeset()
    |> Repo.update()
  end
end

test "refunds an order" do
  order = %Order{status: :paid}

  {:ok, refunded_order} = Order.refund(order)
  assert refunded_order.status == :refunded

  {:ok, updated_order} = Orders.update_order(order)
  assert updated_order.status == :refunded
end

So, I want to update a struct without explicitly defining which attributes are updated. I still want to use the struct’s changeset to make sure that all required fields are set etc. Do you know a way I could achieve this?

I tried the following, but it didn’t pick up all changes:

defmodule Orders do
  def update_order(order) do
     attrs = order |> Map.from_struct() |> Map.drop([:id, :__meta__, :inserted_at, :updated_at])
    update_order(order, attrs)
  end

  def update_order(order, attrs) do
    order
    |> Order.changeset(attrs)
    |> Repo.update()
  end
end

The problem with the approach above was that the Order.changeset compares the order with the attrs and if they didn’t change, then it doesn’t update them. Since the attrs have the same values as the provided order, it never updated anything.

Most Liked

al2o3cr

al2o3cr

The Ecto equivalent of returning an unsaved ActiveRecord object is returning an Ecto.Changeset, not a struct that’s only updated in-memory - then you can pass that directly to functions like Repo.update.

hst337

hst337

It is not possible because this will lead to inconsistencies.

Let’s check out all possible scenarios

  1. You update structure, use updated structure and then call changeset. With this approach, when you use the updated structure, you could’ve used incorrectly set values (because changeset check was not performed yet).
  2. You update structure, call changeset and then use updated changeset. With this approach you’d have to use get_field and family of functions to get the actual data from the structure. But this data may be incorrect too, since it is missing some autogenerated-in-the-database fields, database hooks and all this stuff

So I’d suggest using the approach dedicated by Ecto library: record is separate from it’s changes, changes can be verified and the version of the record with all the changes applied is visible only after interaction with the database (because DBs have hooks, autogenerated fields, etc)

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

I don’t really recommend what you’re doing, but the closest thing I can think of would be to use postgres INSERT ON CONFLICT

order_struct
|> Repo.insert(on_conflict: :replace_all, conflict_target: :id)
sodapopcan

sodapopcan

You generally want to create changesets for such actions. Something like this:

def refund_changeset(%{status: :refunded} = order) do
  order
  |> change()
  |> add_error(:status, "Order already refunded")
end

def refund_changeset(order) do
  order
  |> change(%{status: :refunded})
  |> validate_can_refund() # Custom validation of other criteria that may make a non-refunded order non-refundable
end

Then in your context have an explicit Orders.refund_order/1 function:

def refund_order(order) do
  order
  |> Order.refund_changeset()
  |> Order.update()
end

If you want to stay CRUDy like that, you’re going to have to get a little more creative in checking if it’s valid to refund. The simplest way off the top of my head would be to add another function head to Orders.update/2 context function:

def update_order(%{status: :refunded} = order, _attrs) do
  changeset =
    order
    |> Ecto.Changeset.change()
    |> Ecto.Changeset.add_error(:status, "Order already refunded")

  {:error, changeset}
end

def update_order(order, attrs) do
  # ...
end

There is probably (definitely) a better way to do the CRUD version but just trying to offer something as a starting point.

LostKobrakai

LostKobrakai

Yeah, updating data in place is imo a smell in ecto/elixir. Being explicit and returning a changeset is the way to go, as this cleanly communciates what is been dealt with: Not yet persisted changes.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New

Other popular topics Top

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement