Phoenix和Ecto和SELECTs [英] Phoenix and Ecto and SELECTs
问题描述
我在Phoenix的Ecto模型中建立了一个关联.一个组织有许多OrganizationMembers.在OrganizationMember控制器的Edit方法中,我试图创建一个SELECT元素,该元素将保留所有可供选择的组织.在 edit 定义中,我有以下两行:
I have an association set up in Ecto models in Phoenix. An Organization has many OrganizationMembers. In the OrganizationMember controller's Edit method, I'm trying to create a SELECT element that will hold all of the Organizations to choose from. In the edit definitiion, I've got the following two lines:
# organizations = Enum.to_list(from(o in Organization, order_by: o.name, select: [o.name, o.id]))
organizations = from(o in Organization, order_by: o.name, select: {o.name, o.id})
这是我在模板中显示选择内容的行:
This is my line in the template to show the select:
<%= select f, :organization_id, @organizations, prompt: "Choose your organization" %>
如果我保留第一行的注释,则会在选择的模板上收到此错误:
If I keep the first line commented, I get this error on the template select:
#Ecto.Query协议未实现Enumerable
protocol Enumerable not implemented for #Ecto.Query
如果我使用第一行并注释第二行,则会在控制器中收到此错误:
If I use the first line and comment the second one, I get this error in the controller:
#Ecto.Query协议未实现Enumerable
protocol Enumerable not implemented for #Ecto.Query
如何获取选择以正确显示选择下拉列表和值?顺便说一句,organization_id来自此:
How do I get the select to properly show the select dropdown and the values? BTW the organization_id comes from this:
organization_member = Repo.get!(OrganizationMember, id) |> Repo.preload(:organization)
organization_id = organization_member.organization.id
推荐答案
如错误消息所述,%Ecto.Query{}
不能枚举.如果要带来查询结果,则必须调用存储库并为其查询:
As the error messages say, an %Ecto.Query{}
is not an Enumerable. If you want to bring the query results, you must call the repository and give it the query:
Repo.all from(o in Organization, order_by: o.name, select: {o.name, o.id})
PS:注意,我将select返回的值更改为元组,因为这正是select
所需的形式.
PS: Note I changed the valued returned by select into a tuple because that's what the form select
needs.
这篇关于Phoenix和Ecto和SELECTs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!