How to use Repo.get with a choice like in Repo.one

I'm not sure if this is possible, but I like the fact that Repo.get returns Struct.

I am trying to do something like:

Repo.get(User, id, select: [:id, :name])

How in:

Repo.one(from u in User, where: u.id == ^id, select: [u.id, u.name]

But with Repo.get I cannot understand from the Ecto docs, if possible, and how to do it.

Context: I use Guardian, and the serializer does something like:

def from_token("User:" <> id), do: {:ok, Repo.get(User, id,)}

Therefore, when I call current_resource(conn), I get a user-friendly structure. But this request returns all the user information from db, which I am trying to filter (for example, I do not want the encrypted password to be in mine current_resource(conn).

+4
source share
1 answer

As @Dogbert notes in the comments, the solution:

import Ecto.Query

from(User) |> select([:id, :name]) |> Repo.get(id)

-:

import Ecto.Query

....

def from_token("User:" <> id), do: {:ok, from(User) |> select([:id, :name]) |> Repo.get(id)}

.....

Ecto.Repo docs:

get (queryable, id, opts) get (queryable:: Ecto.Queryable.t, id:: term, opts:: Keyword.t)::   Ecto.Schema.t |   nil |   no_return

, .

, . , .

, get/3, . from(User) |> select([:id, :name]), Repo.get(id)

, user.

phoenix-framework docs :

, . .

, , /, , .

+1

Source: https://habr.com/ru/post/1662072/


All Articles