mbrg

mbrg

Using a `no_attributes` relationship in a calculation

Hi,

I have recently finished the Ash Framework book ,and would like to add some more features to my Tunez app, starting with a friend system.

What I came up with was to model everything with a FriendRequest resource between a source and target user, like in this blog post. A user has (accepted) friend requests, a user Alice is friends with Bob if Alice’s ID appears in Bob’s list of accepted friend requests as either the target or the source.

So far I have been able to set up friendships between users and to list their friends. What I want to do now is to add an is_my_friend calculation which works similarly to the followed_by_me calculation on Artist.

My resources look like this (just the relevant bits, the Tunez resource also has account registration etc.):

defmodule FriendshipTest.Accounts.User do
  # ... snip
  attributes do
    uuid_primary_key :id

    attribute :username, :ci_string do
      allow_nil? false
      public? true
    end
  end

  relationships do
    has_many :friends, FriendshipTest.Accounts.User do
      no_attributes? true
      public? true

      filter expr(
               parent(accepted_friend_requests.target_user_id) in [id, parent(id)] &&
                 parent(accepted_friend_requests.source_user_id) in [id, parent(id)]
             )
    end

    has_many :accepted_friend_requests, FriendshipTest.Accounts.FriendRequest do
      public? true
      no_attributes? true

      filter expr(
               parent(id) in [source_user_id, target_user_id] &&
                 not pending
             )
    end
  end

  calculations do
    calculate :is_my_friend, :boolean, expr(exists(friends, id == ^actor(:id))) do
      public? true
    end
  end
  # ... snip
end

defmodule FriendshipTest.Accounts.FriendRequest do
  # ... snip
  attributes do
    create_timestamp :inserted_at

    attribute :accepted_at, :utc_datetime_usec do
      public? true
    end
  end

  relationships do
    belongs_to :source_user, FriendshipTest.Accounts.User do
      public? true
      allow_nil? false
      primary_key? true
    end

    belongs_to :target_user, FriendshipTest.Accounts.User do
      public? true
      allow_nil? false
      primary_key? true
    end
  end

  calculations do
    calculate :pending, :boolean, expr(is_nil(accepted_at))
  end
  # ...snip
end

This works for befriending users and listing their friends:

iex(1)> [user_a, user_b] = Friendshiptest.Repo.all(FriendshipTest.Accounts.User)
iex(2)> FriendshipTest.Accounts.befriend_user!(user_a, actor: user_b)
iex(3)> FriendshipTest.Accounts.befriend_user!(user_b, actor: user_a)

iex(4)> Ash.load!(user_a, :friends)
# ... database query
%FriendshipTest.Accounts.User{
  id: "48a91eeb-72ab-4161-af63-68742739c58f",
  username: #Ash.CiString<"user_a">,
  is_my_friend: #Ash.NotLoaded<:calculation, field: :is_my_friend>,
  friends: [
    %FriendshipTest.Accounts.User{
      id: "8a5a1841-9c3d-4195-8877-f64c0826f7c7",
      username: #Ash.CiString<"user_b">,
      is_my_friend: #Ash.NotLoaded<:calculation, field: :is_my_friend>,
      friends: #Ash.NotLoaded<:relationship, field: :friends>,
      accepted_friend_requests: #Ash.NotLoaded<:relationship, field: :accepted_friend_requests>,
      __meta__: #Ecto.Schema.Metadata<:loaded, "public", "users">
    }
  ],
  accepted_friend_requests: #Ash.NotLoaded<:relationship, field: :accepted_friend_requests>,
  __meta__: #Ecto.Schema.Metadata<:loaded, "users">
}

iex(5)> Ash.load!(user_b, :friends)
#...
%FriendshipTest.Accounts.User{
  id: "8a5a1841-9c3d-4195-8877-f64c0826f7c7",
  username: #Ash.CiString<"user_b">,
  is_my_friend: #Ash.NotLoaded<:calculation, field: :is_my_friend>,
  friends: [
    %FriendshipTest.Accounts.User{
      id: "48a91eeb-72ab-4161-af63-68742739c58f",
      username: #Ash.CiString<"user_a">,
      is_my_friend: #Ash.NotLoaded<:calculation, field: :is_my_friend>,
      friends: #Ash.NotLoaded<:relationship, field: :friends>,
      accepted_friend_requests: #Ash.NotLoaded<:relationship, field: :accepted_friend_requests>,
      __meta__: #Ecto.Schema.Metadata<:loaded, "public", "users">
    }
  ],
  accepted_friend_requests: #Ash.NotLoaded<:relationship, field: :accepted_friend_requests>,
  __meta__: #Ecto.Schema.Metadata<:loaded, "users">
}

But when I try to load is_my_friend I get this error:

iex(6)> Ash.load!(user_a, :is_my_friend, actor: user_b)
** (Ash.Error.Unknown)
Bread Crumbs:
  > Exception raised in: FriendshipTest.Accounts.User.read

Unknown Error

* ** (RuntimeError) Error while building parent reference: accepted_friend_requests.target_user_id

Query so far:

#Ecto.Query<from u0 in FriendshipTest.Accounts.User, as: 1, select: struct(u0, [:id, :username])>

Current bindings:

%{0 => %{type: :root, path: [], source: FriendshipTest.Accounts.User}}

  (ash_sql 0.2.86) lib/expr.ex:3302: AshSql.Expr.reference_error!/2
  (ash_sql 0.2.86) lib/expr.ex:2283: AshSql.Expr.default_dynamic_expr/6
  (ash_sql 0.2.86) lib/expr.ex:1851: AshSql.Expr.default_dynamic_expr/6
  (ash_sql 0.2.86) lib/expr.ex:1201: AshSql.Expr.default_dynamic_expr/6
  (ash_sql 0.2.86) lib/expr.ex:1851: AshSql.Expr.default_dynamic_expr/6
  (ash_sql 0.2.86) lib/expr.ex:1201: AshSql.Expr.default_dynamic_expr/6
  (ash_sql 0.2.86) lib/filter.ex:38: anonymous fn/2 in AshSql.Filter.add_filter_expression/2
  (elixir 1.18.4) lib/enum.ex:2546: Enum."-reduce/3-lists^foldl/2-0-"/3
    (ash_sql 0.2.86) lib/expr.ex:3302: AshSql.Expr.reference_error!/2
    (ash_sql 0.2.86) lib/expr.ex:2283: AshSql.Expr.default_dynamic_expr/6
    (ash_sql 0.2.86) lib/expr.ex:1851: AshSql.Expr.default_dynamic_expr/6
    (ash_sql 0.2.86) lib/expr.ex:1201: AshSql.Expr.default_dynamic_expr/6
    (ash_sql 0.2.86) lib/expr.ex:1851: AshSql.Expr.default_dynamic_expr/6
    (ash_sql 0.2.86) lib/expr.ex:1201: AshSql.Expr.default_dynamic_expr/6
    (ash_sql 0.2.86) lib/filter.ex:38: anonymous fn/2 in AshSql.Filter.add_filter_expression/2
    iex:6: (file)

Am I missing something obvious?

I have also put the code on GitHub, along with a failing testcase if that helps.

Most Liked

mbrg

mbrg

https://github.com/ash-project/ash/issues/2214

Thanks for the quick reply, lease let me know if I need to change anything.

Where Next?

Popular in Questions Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement