Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir how to get map from ecto

I'd like to get a data structure from ecto which allow to write iteraly something like this in my HTML :

<%= genders.name %>

So I think I should have :

[{name: "Male", id: 1}, {name: "Female", id: 2}]

Right now my controller run well

defmodule HexProjectWeb.LandingController do
  use HexProjectWeb, :controller

  alias HexProject.Gender

  def index(conn, _params) do
    genders = HexProject.Repo.all(Gender) |> Enum.map(&{&1.name, &1.id})

    conn
    |> assign(:genders, genders)
    |> render("index.html")
    #render conn, "index.html", genders: genders
  end
end

But it return me genders like this:

[{Male, 1}, {Female, 2}]

And I don't know how to show this.

So I tried

genders = HexProject.Repo.all(
  from g in Gender,
  select: %{name: g.name, id: g.id}
)

And it return me an error

function HexProjectWeb.LandingController.init/1 is undefined (module HexProjectWeb.LandingController is not available)

edit: full error

error rendering view

edit2: router.ex

defmodule HexProjectWeb.Router do
  use HexProjectWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", HexProjectWeb do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index
    get "/landing", LandingController, :index
    resources "/genders", LandingController
  end

  # Other scopes may use custom stacks.
  # scope "/api", HexProjectWeb do
  #   pipe_through :api
  # end
end

Thank you for help.

like image 606
Gotrek Avatar asked Oct 28 '22 15:10

Gotrek


1 Answers

You could fix those problems separately.

For your first approach, you should have:

genders = HexProject.Repo.all(Gender) |> Enum.map(&%{name: &1.name, id: &1.id})

For the second approach, where you're building the query in your controller, you should add import at the top of the file, but inside your controller definition, eg:

defmodule HexProjectWeb.LandingController do
  use HexProjectWeb, :controller

  import Ecto.Query # add this line

  alias HexProject.Gender

In your first attempt, you are actually building a tuple, it should be replaced with correct map syntax (%{} instead of {}).

Second problem you've encountered is unfortunately related to the fact you're using macro, and truly it relates to the lack of availability of from function in your controller.

Hope that helps!

like image 126
Paweł Dawczak Avatar answered Nov 08 '22 10:11

Paweł Dawczak