Phoenix Elixir Assistant for Linked Model List

I have an application in which I list parents and children. When I add a child, I need the parent list to appear as a list. Is there something like collection_select in Rails available in Phoenix? I would like to show the username and use user_id as a parameter.

I also want to cover the list of parents by site_id.

+6
source share
2 answers

You can use the select / 4 function of Phoenix.HTML.Form .

In your controller, you can get selections to parents asking:

 query = from(p in Parent, select: {p.id, p.name}) parents = Repo.all(query) 

The reason we need this request is to format the values ​​in the expected format:

The values ​​are expected to be enumerable, containing two-position tuples (for example, maps and keyword lists) or any enumerable in which the element will be used as a key and value for the generated selection.

Then you can use select/4 in your template:

 <%= select f, :parent_id, @parents ,class: "form-control" %> 

You can also convert records using Enum.map/2 if you already have parents:

 parents = Repo.all(Parent) |> Enum.map(&{&1.id, &1.name}) 
+8
source

controller

 all_parents = Repo.all from p in Parent, select: {p.name, p.id} 

ex

 <%= select f, :parent_id, @all_parents %> 
0
source

All Articles