问题
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