How do I do this SQL UPDATE-query in Ash?

I want to update a row in a database table if it exists, and otherwise return an error. In SQL I would do something like this:

UPDATE hats SET activation_token = null, activated = NOW() WHERE activation_token = ...


I tried with an update-action in Ash, because that seemed like the natural first thing to try, but then I have to give it a record as a first argument and I don't have a record, that's what I want to lookup with the activation_token, and now every other solution doesn't really fit into my idea of how this should be solved. How should I go about solving this? What's the cleanest or maybe most idiomatic way to write this kind of functionality?
Solution
require Ash.Query # needed for filter

bulk_result =
  Hats
  |> Ash.Query.for_read(:read_action_name, %{}, scope: your_scope)
  |> Ash.Query.filter(activation_token == ^activation_token) 
  |> Ash.bulk_update(:update_action_name, %{your: changes}, scope: your_scope, return_records?: true)

if bulk_result.satus != :success || length(bulk_result.records) == 0 do
  raise "some kind of error"
end
Was this page helpful?