Phoenix 和 Ecto 以及 SELECT
Phoenix and Ecto and SELECTs
我在凤凰城的 Ecto 模型中建立了一个协会。一个组织有许多组织成员。在 OrganizationMember 控制器的 Edit 方法中,我试图创建一个 SELECT 元素,它将包含所有可供选择的组织。在 edit 定义中,我有以下两行:
# 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})
这是我在模板中显示的行 select:
<%= select f, :organization_id, @organizations, prompt: "Choose your organization" %>
如果我保留第一行注释,我会在模板上收到此错误 select:
protocol Enumerable not implemented for #Ecto.Query
如果我使用第一行并注释第二行,我会在控制器中收到此错误:
protocol Enumerable not implemented for #Ecto.Query
如何让 select 正确显示 select 下拉列表和值?顺便说一句,organization_id 来自于此:
organization_member = Repo.get!(OrganizationMember, id) |> Repo.preload(:organization)
organization_id = organization_member.organization.id
正如错误消息所说,%Ecto.Query{}
不是可枚举的。如果要带查询结果,必须调用存储库,给它查询:
Repo.all from(o in Organization, order_by: o.name, select: {o.name, o.id})
PS:请注意,我将 select 返回的值更改为一个元组,因为这是 select
需要的形式。
我在凤凰城的 Ecto 模型中建立了一个协会。一个组织有许多组织成员。在 OrganizationMember 控制器的 Edit 方法中,我试图创建一个 SELECT 元素,它将包含所有可供选择的组织。在 edit 定义中,我有以下两行:
# 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})
这是我在模板中显示的行 select:
<%= select f, :organization_id, @organizations, prompt: "Choose your organization" %>
如果我保留第一行注释,我会在模板上收到此错误 select:
protocol Enumerable not implemented for #Ecto.Query
如果我使用第一行并注释第二行,我会在控制器中收到此错误:
protocol Enumerable not implemented for #Ecto.Query
如何让 select 正确显示 select 下拉列表和值?顺便说一句,organization_id 来自于此:
organization_member = Repo.get!(OrganizationMember, id) |> Repo.preload(:organization)
organization_id = organization_member.organization.id
正如错误消息所说,%Ecto.Query{}
不是可枚举的。如果要带查询结果,必须调用存储库,给它查询:
Repo.all from(o in Organization, order_by: o.name, select: {o.name, o.id})
PS:请注意,我将 select 返回的值更改为一个元组,因为这是 select
需要的形式。