PJextra
Best way to delete values in a Struct
I want to delete some values from a Struct that results of an Ecto Repo.all().
I found this question (https://stackoverflow.com/questions/29351563/whats-a-good-solution-to-drop-nil-value-in-a-struct-for-elixir) which solves it but makes me change from a Struct to a Map.
This question is from 2015.
As of today is there a better/simpler way of deleting a few values while keeping the rest of the Struct?
Marked As Solved
voger
I haven’t played with ecto much yet so what I say take it with a grain of salt.
My guess is that you try to get various columns from all the rows in your table based on some conditional logic. i.e.
if (user_requests == username)
bring username
if (user_requests == email)
bring email also
bring_all_that_requested()
In this case you can take advantage the fact that ecto queries are composable. So you can mix and mach your queries as you wish. Take a look at this Ecto.Query — Ecto v3.14.0
Update: I tried this myself in iex and indeed can’t compose select
iex(18)> query = from u in User, select: %{username: u.username}
query = from u in User, select: %{username: u.username}
#Ecto.Query<from u in Qssite.User, select: %{username: u.username}>
iex(19)> Repo.all(query)
Repo.all(query)
...
iex(20)> query = from u in query, select: %{email: u.email}
query = from u in query, select: %{email: u.email}
** (Ecto.Query.CompileError) only one select expression is allowed in query
but one can use struct or map for that.
P.S.: If you really want to delete that key then I think Map.delete/2 and Map.drop/2 should suffice. No need to convert to map. Or you could simply set the keys to nil.
user = Repo.get(User, 1)
user = user = %{user| email: nil, username: nil}
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








