Elixir Ecto:如何在变更集中设置belongs_to关联

问题描述 投票:0回答:1

我有点困惑如何实际设置与变更集的关联。我的模型中有这段代码:

defmodule MyApp.MemberApplication do
  use MyApp.Web, :model
  use Ecto.Schema
  use Arc.Ecto.Schema

  alias MyApp.Repo
  alias MyApp.MemberApplication

  schema "applications" do
    field :name, :string
    field :email, :string
    field :time_accepted, Ecto.DateTime
    field :time_declined, Ecto.DateTime
    belongs_to :accepted_by, MyApp.Admin
    belongs_to :declined_by, MyApp.Admin

    timestamps()
  end

  def set_accepted_changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:time_accepted, :accepted_by_id])
    |> cast_assoc(params, :accepted_by)
    |> set_time_accepted
  end

  defp set_time_accepted(changeset) do
    datetime = :calendar.universal_time() |> Ecto.DateTime.from_erl()
    put_change(changeset, :time_accepted, datetime)
  end
end

我想保存与执行特定操作(接受或拒绝会员申请)的

Admin
的关联以及时间戳。时间戳的生成有效,但是当我尝试保存关联时,我总是收到错误

** (FunctionClauseError) no function clause matching in Ecto.Changeset.cast_assoc/3

这就是我想要设置关联的方式:

iex(26)> application = Repo.get(MemberApplication, 10)
iex(27)> admin = Repo.get(Admin, 16)
iex(28)> changeset = MemberApplication.set_accepted_changeset(application, %{accepted_by: admin})
elixir ecto
1个回答
17
投票

谢谢@Dogbert。这就是我让它工作的方法

defmodule MyApp.MemberApplication do
  use MyApp.Web, :model
  use Ecto.Schema
  use Arc.Ecto.Schema

  alias MyApp.Repo
  alias MyApp.MemberApplication

  schema "applications" do
    field :name, :string
    field :email, :string
    field :time_accepted, Ecto.DateTime
    field :time_declined, Ecto.DateTime
    belongs_to :accepted_by, MyApp.Admin
    belongs_to :declined_by, MyApp.Admin

    timestamps()
  end

  def set_accepted_changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:time_accepted, :accepted_by_id])
    # Change cast_assoc 
    |> cast_assoc(:accepted_by)
    |> set_time_accepted
  end

  defp set_time_accepted(changeset) do
    datetime = :calendar.universal_time() |> Ecto.DateTime.from_erl
    put_change(changeset, :time_accepted, datetime)
  end
end

然后预加载关联,直接设置ID。或者直接在查询中执行:

iex(26)> application = Repo.get(MemberApplication, 10)
iex(27)> application = Repo.preload(application, :accepted_by)
iex(28)> admin = Repo.get(Admin, 16)
iex(29)> changeset = MemberApplication.set_accepted_changeset(application, %{accepted_by_id: admin.id})
© www.soinside.com 2019 - 2024. All rights reserved.