How to get value from Repo.all in controller

I try to get nested value in returned from Repo.all.

I know how to show values in templates.
However I would like to get data in controller.

In template

      <%= for member <- @members do %>
               <%= member.member_name %>
      <% end %>

In controller

members = Repo.all(Members)
# I would like to get value of first one (aaa).

[%Apps.Sample.Member{__meta__: #Ecto.Schema.Metadata<:loaded, "members">, member_name: "aaa"}, %Apps.Sample.Member{__meta__: #Ecto.Schema.Metadata<:loaded, "members">, member_name: "bbb"} ]

Are there any way to resolve it?

If you want Repo module to be available in controller, you need to use it explicitly just like the model file. but its not a good way to do it. I would suggest you to fetch the data via model.

In controller
members = Member.list_all

In member.ex file
defmodule Member do
  import Ecto.Query, warn: false # if you still want to use it in controller copy this line to the controller
  alias Module.Repo # and this line too, replace module with your module
  def list_all do
    Repo.all(Member)
  end

   def get_member!(id), do: Repo.get!(Member, id) # to find member by id
end

And can you please explain this

Hello,
you can obtain the first element of the list bound to members using List.first/1

members = Repo.all(Members)
# I would like to get value of first one (aaa).
first_member = List.first(members)

hth

1 Like

Also you can write your schema code like this

 def list_all do
    Member
    |> Repo.all()
  end

This will help you when you want to combine multiple queries together also this is called compositions or query compositions