Reputation: 8461
I'm trying to scope records to what belong to the current user. But I'm not having much success. Here is what I'm trying:
def show(conn, %{"id" => id}) do
user_id = Map.get(Statcasters.Guardian.Plug.current_resource(conn), :id)
user = Repo.get!(User, user_id) |> Repo.preload(:leagues)
league = Repo.get(user.leagues, id)
end
But I'm getting this error:
** (Protocol.UndefinedError) protocol Ecto.Queryable not implemented for [%Statcasters.League{__meta__: #Ecto.Schema.Metadata<:loaded, "leagues">, id: 16, inserted_at: ~N[2018-05-05 22:13:23.675833], name: "Cam's League", player_limit: 10, updated_at: ~N[2018-05-05 22:13:23.675843], users: #Ecto.Association.NotLoaded<association :users is not loaded>, users_leagues: #Ecto.Association.NotLoaded<association :users_leagues is not loaded>}]
What makes records "queryable"? I guess passing a list into the Repo.get is not valid. So, what should I pass in that would properly scope the leagues to the current user?
Upvotes: 0
Views: 137
Reputation: 15045
The problem is that user.leagues
is a List
of preloaded associated records. If you need to find a record in that list, what about using Enum.find/3 for this:
Enum.find user.leagues, fn league -> league.id == id end
Otherwise, a league
can just be loaded by id
out of Repo
, you don't need to scope leagues
by user_id
, since there's one unique record with the provided id
:
Repo.get League, id
Upvotes: 2