如何与ecto 2建立多对多关系?作为一个示例应用程序,我想创建一个可以在多个类别中的帖子.这些类别已经存在.例如:
[%Category{id: "1", name: "elixir"}, %Category{id: "2", name: "erlang"}]
Run Code Online (Sandbox Code Playgroud)
我正在使用Ecto 2 beta 0.示例项目名为Ecto2.
我定义了两个模型:
defmodule Ecto2.Post do
use Ecto2.Web, :model
use Ecto.Schema
schema "posts" do
field :title, :string
many_to_many :categories, Ecto2.Category, join_through: "posts_categories", on_replace: :delete
timestamps
end
@required_fields ~w(title)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_assoc(:categories) # not suitable?
end
end
defmodule Ecto2.Category do
use Ecto2.Web, :model
schema "categories" do
field :name, :string
timestamps
end
@required_fields ~w(name)
@optional_fields ~w()
def changeset(model, …Run Code Online (Sandbox Code Playgroud) 我在凤凰城的Ecto模型中建立了一个关联.组织有许多组织成员.在OrganizationMember控制器的Edit方法中,我正在尝试创建一个SELECT元素,该元素将包含所有可供选择的组织.在编辑定义中,我有以下两行:
# 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})
Run Code Online (Sandbox Code Playgroud)
这是我在模板中显示选择的行:
<%= select f, :organization_id, @organizations, prompt: "Choose your organization" %>
Run Code Online (Sandbox Code Playgroud)
如果我保留第一行注释,我会在模板上选择以下错误:
protocol Enumerable未针对#Ecto.Query实现
如果我使用第一行并注释第二行,我在控制器中收到此错误:
protocol Enumerable未针对#Ecto.Query实现
如何让select正确显示选择下拉列表和值?BTW,organization_id来自于:
organization_member = Repo.get!(OrganizationMember, id) |> Repo.preload(:organization)
organization_id = organization_member.organization.id
Run Code Online (Sandbox Code Playgroud)