RodolfoSilva

RodolfoSilva

How can I compute an attribute’s value based on an argument without set `require_atomic?` to false?

For instance, certain attributes are stored in the database as utc_datetime, and I need to assign their values conditionally based on a boolean argument.

defmodule MyApp.AshDomains.Accounts.Preferences do
  use Ash.Resource,
    domain: MyApp.AshDomains.Accounts,
    data_layer: AshPostgres.DataLayer,
    extensions: [AshArchival.Resource]

  alias Ash.Changeset 

  postgres do
    table "account_preferences"
    repo MyApp.Repo
  end

  archive do
    attribute :deleted_at
  end

  changes do
    change fn changeset, _context ->
      notification_enabled_at = Changeset.get_attribute(changeset, :notification_enabled_at)
      notification_enabled = Changeset.get_argument(changeset, :notification_enabled)

      cond do
        is_nil(notification_enabled_at) and notification_enabled == true ->
          Changeset.force_change_attribute(changeset, :notification_enabled_at, expr(now()))

        not is_nil(notification_enabled_at) and notification_enabled == false ->
          Changeset.force_change_attribute(changeset, :notification_enabled_at, nil)

        true ->
          changeset
      end
    end
  end

  actions do
    defaults [:read, :destroy]

    create :create do
      argument :notification_enabled, :boolean, allow_nil?: false
    end

    update :update do
      argument :notification_enabled, :boolean, allow_nil?: false
    end
  end

  attributes do
    uuid_v7_primary_key :id

    attribute :notification_enabled_at, :utc_datetime
  end

  calculations do
    calculate :notification_enabled, :boolean, expr(not is_nil(notification_enabled_at))
  end
end

When I try to set the attribute value, I get an error about implementing atomic/3, but I don’t think it should be atomic, it’s just a derived value.

[warning] Unhandled error in form submission for Salao365.AshDomains.Appointments.Product.update

This error was unhandled because Ash.Error.Framework.MustBeAtomic does not implement the AshPhoenix.FormData.Error protocol.

** (Ash.Error.Framework.MustBeAtomic) Salao365.AshDomains.Appointments.Product.update must be performed atomically, but it could not be

Reason: Ash.Resource.Change.Function does not implement atomic/3

See Update Actions — ash v3.29.3 for more on atomics.

@zachdaniel do you have any suggestions?

I was expecting something like this:

change set_new_attribute(:notification_enabled_at, expr(if arg(:notification_enabled) == true, do: now(), else: nil))

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

Three things:

  1. a misunderstanding to clear up
  2. Generally “how to make a change that works atomically”
  3. How I’d actually do this one

Misunderstanding: When can you use expressions to change attributes

There is only one place you can change attributes using expressions, and that is in atomic_update statements via Ash.Changeset.atomic_update or change atomic_update. This is only supported for update actions.

For example:

change atomic_update(:notification_enabled_at, expr(now())

Making changes safe to do atomically

The reason function changes like that can’t be done atomically is because it has to be explicitly annotated as supporting atomic behavior by defining the atomic/3 callback. You can actually implement a change as a module, and define the atomic/3 callback. If you want this logic to support both create and update actions, and be abstracted into a single module, this is the approach to use.

For example:

defmodule YourApp.YourDomain.YourResource.Changes.SetEnabledAt do
   use Ash.Resource.Change

  def change(%{action_type: :create} = changeset, _, _) do
    Ash.Changeset.force_change_attribute(changeset, :notification_enabled_at, DateTime.utc_now())
  end

  def change(changeset, _, _) do
    Ash.Changeset.atomic_update(changeset, :notification_enabled_at, 
      expr(fragment("LEAST(?, ?)", ^atomic_ref(:notification_enabled_at), now()))
    )
  end

  # define the `atomic/3` callback. The behavior is the same as `change`, so no special logic needed.
  def atomic(changeset, opts, context) do
    {:ok, change(changeset, opts, context)}
  end
end

How I’d probably do it

changes do
  change set_attribute(:notification_enabled_at, &DateTime.utc_now/0), 
    where: argument_equals(:notification_enabled, true),
    on: :create

  change atomic_update(:notification_enabled_at, expr(
      fragment("LEAST(?, ?)", ^atomic_ref(:notification_enabled_at), now())
    ) ,
    where: argument_equals(:notification_enabled, true),
    on: :update
end

Also Liked

zachdaniel

zachdaniel

Creator of Ash

It’s for all changes and validations. You can use validations in the where clause to make other changes/validations conditional.

Last Post!

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54006 488
New
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New

We're in Beta

About us Mission Statement