Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show all records of a model in Phoenix select field

I have following models...

  1. Page
  2. Category

i have following code in new action of page_controller.ex

def new(conn, _params) do
  changeset = Page.changeset(%Page{})
  categories = Repo.all(Category)
  render(conn, "new.html", changeset: changeset, categories: categories)
end

I have following code for select field in page/new.html.eex

<div class="form-group">
  <%= label f, :category_id, "Parent", class: "control-label" %>
  <%= select f, :category_id, @categories ,class: "form-control" %>
</div>

It should show all categories in select field so i can choose one category for the page but unfortunately i am unable to find the problem. if you have any suggestion please let me know.

like image 795
Murtza Avatar asked Nov 19 '15 13:11

Murtza


1 Answers

The select/4 function expects a list of tuples for the 3rd argument.

From the docs:

Values are expected to be an Enumerable containing two-item tuples (like maps and keyword lists) or any Enumerable where the element will be used both as key and value for the generated select.

Try changing your controller to:

categories = Repo.all(Category) |> Enum.map(&{&1.name, &1.id})

This can also be done at the query level:

query = from(c in Category, select: {c.name, c.id})
categories = Repo.all(query)

See Phoenix: Ordering a query set for an explanation of defining a query as a function in your model.

like image 177
Gazler Avatar answered Oct 20 '22 19:10

Gazler