rbino

rbino

Ash Core Team

Publishing an event with the previous value of an attribute with PubSub

Hey everyone!

In my app I have this resource (some parts omitted):

defmodule MyApp.Vote do
  use Ash.Resource,
    data_layer: AshPostgres.DataLayer

  actions do
    create :cast do
      argument :poll_id, :uuid, allow_nil?: false
      argument :option_id, :uuid, allow_nil?: false

      upsert? true
      upsert_identity :unique_voter_per_poll

      change manage_relationship(:poll_id, :poll, type: :append_and_remove)
      change manage_relationship(:option_id, :option, type: :append_and_remove)
      change relate_actor(:voter)
    end
  end

  relationships do
    belongs_to :poll, Poll do
      primary_key? true
      allow_nil? false
    end

    belongs_to :option, Option do
      primary_key? true
      allow_nil? false
    end

    belongs_to :voter, Voter do
      primary_key? true
      allow_nil? false
    end
  end

  identities do
    identity :unique_voter_per_poll, [:voter_id, :poll_id]
  end

  code_interface do
    define_for MyApp.Voting
    define :cast, args: [:poll_id, :option_id]
  end
end

If a voter casts their vote for another option in the same poll, this is an upsert so the new option id overwrites the old one.

Now, I want to publish updates on a pubsub because I want to display (and update) the count of votes for each option in a Live View. This means that when I cast a vote, I want to receive a vote event for the option_id, but I also want to receive an unvote event for the previous option_id.

What is the recommended way to do this?

Marked As Solved

rbino

rbino

Ash Core Team

I think I’ve found a workaround: I’ve added a custom change that reads the current option.

defmodule Tabemono.Voting.Vote.Changes.StorePreviousOption do
  use Ash.Resource.Change
  require Ash.Query

  def change(changeset, _opts, ctx) do
    poll_id = Ash.Changeset.get_argument(changeset, :poll_id)
    voter_id = ctx.actor.id

    previous_vote =
      Tabemono.Voting.Vote
      |> Ash.Query.lock("FOR UPDATE NOWAIT")
      |> Ash.Query.filter(poll_id: poll_id, voter_id: voter_id)
      |> Tabemono.Voting.read_one!()

    if previous_vote do
      Ash.Changeset.put_context(changeset, :old_option_id, previous_vote.option_id)
    else
      changeset
    end
  end
end

To be extra careful, I’ve added a row lock. This way, in the (unlikely) event that the same user tries to update the vote from two different locations, one of them should fail, ensuring a single notification is sent for that old option id.

After that, it’s just a matter of reading the changeset context in the notification that gets sent. I would’ve preferred to put this information in the notification metadata instead, but I’m not sure how to control it.

Is this solutions reasonable or does it have any problem?

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
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 t...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement