Elixir Phoenix helper for associated model list

2020-06-18 07:18发布

I have an app in which I list parents and children. When I add a child, I need to get a list of parents to be shows as a drop list. Is there something like a collection_select in Rails available in Phoenix? I would like to display the name of the user and use user_id as a param.

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

2条回答
来,给爷笑一个
2楼-- · 2020-06-18 07:37

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

In your controller you can fetch fetch the parents with a query:

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

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

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.

You can then use select/4 in your template:

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

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

parents = Repo.all(Parent) |> Enum.map(&{&1.id, &1.name})
查看更多
We Are One
3楼-- · 2020-06-18 07:39

controller

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

eex

<%= select f, :parent_id, @all_parents %>
查看更多
登录 后发表回答