Phoenix and Ecto and SELECTs

核能气质少年 提交于 2020-01-14 14:39:28

问题


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:

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:

protocol Enumerable not implemented for #Ecto.Query

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

回答1:


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: Note I changed the valued returned by select into a tuple because that's what the form select needs.



来源:https://stackoverflow.com/questions/32576899/phoenix-and-ecto-and-selects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!