Ecto query issue get matching ids from one to many relation

Hey I am trying to execute an ecto query similar to one I already have but it does not want to work, also how would i return a list of the matches?

  def get_recording_list(user) do
recording_query =
  from(
    r in Recording,
    where: r.user_id == user.id,
    select: r
  )

Repo.all(recording_query)
end

the relation between a user and a recording is one to many

What does “it does not want to work” mean for you?

Do you get an error? Is the data you receive is different from what you expect? If the latter, how do the involved schemas look like?

PS: I’m not using ecto very much, but don’t you need to pin user.id?

yeah i tried it with pin, and the error looks like this:

warning: variable "r" does not exist and is being expanded to "r()", please use parentheses to
remove the ambiguity or change the variable name
  lib/userteam1_web/controllers/recording_controller.ex:11

warning: variable "r" does not exist and is being expanded to "r()", please use parentheses to
remove the ambiguity or change the variable name
  lib/userteam1_web/controllers/recording_controller.ex:12


== Compilation error in file lib/userteam1_web/controllers/recording_controller.ex ==
** (CompileError) lib/userteam1_web/controllers/recording_controller.ex:12: cannot use ^user.id() outside of match clauses
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    (stdlib) lists.erl:1355: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    (stdlib) lists.erl:1355: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    (stdlib) lists.erl:1355: :lists.mapfoldl/3

And without the pin?

It looks a bit as if the from is not what it should be…

do you have import Ecto.Query in the module?

def get_recording_list(user) do
  recording_query =
    from(
      r in Recording,
      where: r.user_id == ^user.id
    )
  Repo.all(recording_query)
end

should work…

2 Likes

fml thanks dude

1 Like

great, the error message ought to be improved when forgetting to import Ecto.Query

not quite sure where that issue belongs though.

1 Like

ok got another error, when I am trying to use the result of that query, it logs it out niely, but when i want to send it back from my view like this:
recording_list: recording_list
then it gives an error:

 (Poison.EncodeError) unable to encode value: {nil, "recordings"}
        (poison) lib/poison/encoder.ex:383: Poison.Encoder.Any.encode/2
        (poison) lib/poison/encoder.ex:227: anonymous fn/4 in Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3

is there some trick to just send the list?

if someone else has this issue i think this should help:
https://stackoverflow.com/questions/33281803/returning-a-list-gives-poison-encodeerror-unable-to-encode-value

Well, in theory, there should have been somewhere a message telling you that from/1 were an unknown funktion.