Elixir Phoenix帮助器,用于关联的模型列表 [英] Elixir Phoenix helper for associated model list

查看:64
本文介绍了Elixir Phoenix帮助器,用于关联的模型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列出父母和孩子的应用程序.当我添加一个孩子时,我需要获得一个父母列表以作为放映列表显示. Phoenix中有可用的Rails中的collection_select之类的东西吗?我想显示用户名,并将user_id用作参数.

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.

我还想通过site_id来确定父级列表的范围.

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

推荐答案

您可以使用Phoenix.HTML.Form中的"noreferrer> select/4 函数.

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:

值应该是包含两个项目元组(例如映射和关键字列表)的Enumerable,或者是将元素用作生成的select的键和值的任何Enumerable.

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.

然后您可以在模板中使用select/4:

You can then use select/4 in your template:

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

如果您已经有父母,也可以使用Enum.map/2转换记录:

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})

这篇关于Elixir Phoenix帮助器,用于关联的模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆