josefrichter

josefrichter

Turn this query into a preload

I have schema a Class has_many User through Enrollment. Currently I have a single enrollments join table, that holds additional data like processed_at parameter.

I am displaying to a user a list of his classes, and need to display his rank (in fact row_number) in each class, which is derived from processed_at parameter. i.e. something like “you are 5th in class Foo, and 7th in class Bar”.

In my live view I am grabbing the user and his enrollments separately:

current_user = Accounts.get_user_by_session_token(session["user_token"])
current_user_enrollments = Accounts.get_user_enrollments(current_user.id)

the first one is standard phoenix auth function, the second one is the more tricky one:

def get_user_enrollments(user_id) do
    enrollments_with_rank =
      from e in Enrollment,
      select: e,
      # this partitions e by class_id and assigns row_number within that partition
      select_merge: %{rank: over(row_number(), partition_by: e.class_id, order_by: e.processed_at)}

    user_enrollments =
      from ex in subquery(enrollments_with_rank),
      where: ex.user_id == ^user_id

    Repo.all(user_enrollments)

  end

I can’t seem to figure out a syntax that would allow me to do this within a preload. This is a function I tried to create:

def preload_ranked_enrollments(user) do
    enrollments_with_rank =
      from e in Enrollment,
      select: e,
      select_merge: %{rank: over(row_number(), partition_by: e.class_id, order_by: e.processed_at)} # assigns rank by processed_at

    user
    |> Repo.preload(enrollments: enrollments_with_rank)
    |> Repo.preload(enrollments: [:class])
  end

and then call it from liveview this way:

current_user = Accounts.get_user_by_session_token(session["user_token"])
    |> Accounts.preload_ranked_enrollments()

However, it seems like the query in preload_ranked_enrollments actually somehow applies where: e.user_id == ^(user.id) because it always returns all enrollments with rank 1. Meaning if I got enrollments with given class_id and user_id, it would always return just 1 row and obviously give it rank 1. Is this something that Repo.preload actually does? Does it somehow inject that additional where clause into the query?

Note: I use terms “rank” and “row_number” interchangeably here, even though in postgres these are two different things and I am aware of the difference. I initially used the term “rank” in my schema, but getting row_number (always unique) rather than rank from postgres. Will probably change this to avoid confusion in code in future.

Thank you.

First Post!

fuelen

fuelen

yes, you can inspect this in logs.
Try to wrap enrollments_with_rank in preload_ranked_enrollments function into a subquery, as you did in your first example.

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
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
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Other popular topics 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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
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
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement