silverdr

silverdr

Has_many through load selected associated columns

Building on the example from another thread:
https://forum.elixirforum.net/t/many-to-many-once-again-extra-data-on-the-join-table/
User has many Chatroom through UsersChatrooms.

Now, I would like to get names and ids of given user’s chatrooms. I surely can do for example:

user = Repo.preload(user, :chatrooms)

but this will load “everything” from both final and join tables, while I’d rather do something like Rails’ pluck or at least select so that only columns I am interested in are queried. What are the “correct” ways of doing this with Ecto associations?

Alternatively already while fetching the user record

Marked As Solved

LostKobrakai

LostKobrakai

You can use ecto query to select what you need. There’s not really a high level API for that in ecto.

query = 
  from cr in Chatroom, 
    join: ucr in assoc(:users_chatrooms), 
    on: ucr.user_id == ^user_id and ucr.chatroom_id == cr.id,
    select: map(cr, [:id, :name])

Repo.all(query)

or

user
|> Ecto.assoc(:chatrooms)
|> select([cr], map(cr, [:id, :name])
|> Repo.all()

Also Liked

LostKobrakai

LostKobrakai

Ecto only fetches the fields present in the schema anyways. You could even have multiple schemas for a single table, but different use cases. If you’re hardly fetching all fields of a schema I’d wonder if the schema is well defined or if you’d not rather want to split it into multiple.

LostKobrakai

LostKobrakai

Ecto is far more geared towards giving developers the ability to deal with the sql. It’s not an ORM and doesn’t try to be. One could probably built one on top of ecto. I can see this not being great when trying to get things of the ground, but it’s really great once you need to maintain that thing flying.

dimitarvp

dimitarvp

Yep, more or less. And it’s important to remember that Ecto is explicit: it tries very hard not to do things you didn’t ask it to do.

dimitarvp

dimitarvp

I sympathize with the need. You can take it one step further by making helpers for it in your context/domain modules, e.g. with the second coding snippet that @LostKobrakai showed you like so:

defmodule MyApp.Users do
  def with_chatroom_names(user) do
    user
    |> Ecto.assoc(:chatrooms)
    |> select([cr], map(cr, [:id, :name])
    |> Repo.all()
  end
end

And it becomes intuitive to read the consuming modules when they do stuff like Users.with_chatroom_names(user) |> do_other_stuff() …IMO anyway; naming is hard).

I was a Rails dev too, long ago (for 6.5 years). I still sometimes miss bits and pieces from it but as time went by I gravitated towards preferring to get my hands a little more dirty for the added peace of mind that when looking at the app’s code then what I see is exactly what I get.

But again, if you find that clunky, nothing stops you from emulating a few favourite Rails-like idioms in your projects, or even spin them off to internal company libraries (I’ve done so in the past).

sodapopcan

sodapopcan

I went a little too far with my answer by extracting it to a function when obviously @LostKobrakai 's a way better version. My point was just that Ecto is much faster than ActiveRecord (when you are creating AR objects) so it’s not the end of the world to grab all the fields but that is really neither here nor there.

Moving on from pluck, from what you wrote I get the impression you haven’t grasped the full power of composability. You certainly shouldn’t be needing to write SQL first to turn it into Ecto with any regularity. I’ve found Ecto to be incredibly concise and I don’t miss AR even a little. A lot of reusable little one line query helpers can go a really long way. I would have to see examples of what you’re doing, though (not suggesting you want to share, of course :sweat_smile:)

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
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
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
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
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement