(RuntimeError)不支持使用cast / 4转换关联,而是使用cast_assoc / 3

时间:2017-11-06 01:43:24

标签: elixir ecto

我不明白这个错误,我搜索了很多。非示例中显示多个关联? 这是代码。

我的访问列表:

defmodule Db.AccessList do
    use Ecto.Schema

    schema "access_lists" do
        belongs_to :user_id, Db.User
        belongs_to :role_id, Db.Role
        belongs_to :asset_id, Db.Asset
        belongs_to :project_id, Db.Project

        timestamps()
    end

    def changeset(model, params \\ %{}) do
            model
            |> Ecto.Changeset.cast(params, [:user_id, :role_id, :asset_id, :project_id])
            |> Ecto.Changeset.validate_required([:user_id, :role_id])
    end
end

试验:

defmodule AccessListTest do
    alias Db.{ AccessList }
    use ExUnit.Case

    @valid_attr %{user_id: 1, role_id: 1, asset_id: 1, project_id: 1 }

    @tag :wip
    test "ACCESSLIST.1 valid attribute" do
        changeset = AccessList.changeset(%AccessList{}, @valid_attr)
        assert changeset.valid?
    end

    @tag :wip
    test "ACCESSLIST.2 invalid attribute" do
        invalid_attr = Map.put(@valid_attr, :user_id, nil)
        changeset = AccessList.changeset(
            %AccessList{}, invalid_attr
        )
        refute changeset.valid?
    end
end

这是错误:

......

  1) test ACCESSLIST.1 valid attribute (AccessListTest)
     test/access_list_test.exs:8
     ** (RuntimeError) casting assocs with cast/4 is not supported, use cast_assoc/3 instead
     code: changeset = AccessList.changeset(%AccessList{}, @valid_attr)
     stacktrace:
       (ecto) lib/ecto/changeset.ex:485: Ecto.Changeset.type!/2
       (ecto) lib/ecto/changeset.ex:464: Ecto.Changeset.process_param/7
       (elixir) lib/enum.ex:1826: Enum."-reduce/3-lists^foldl/2-0-"/3
       (ecto) lib/ecto/changeset.ex:449: Ecto.Changeset.cast/6
       (db) lib/db/access_list.ex:15: Db.AccessList.changeset/2
       test/access_list_test.exs:10: (test)



  2) test ACCESSLIST.2 invalid attribute (AccessListTest)
     test/access_list_test.exs:15
     ** (RuntimeError) casting assocs with cast/4 is not supported, use cast_assoc/3 instead
     code: changeset = AccessList.changeset(
     stacktrace:
       (ecto) lib/ecto/changeset.ex:485: Ecto.Changeset.type!/2
       (ecto) lib/ecto/changeset.ex:464: Ecto.Changeset.process_param/7
       (elixir) lib/enum.ex:1826: Enum."-reduce/3-lists^foldl/2-0-"/3
       (ecto) lib/ecto/changeset.ex:449: Ecto.Changeset.cast/6
       (db) lib/db/access_list.ex:15: Db.AccessList.changeset/2
       test/access_list_test.exs:18: (test)



Finished in 0.3 seconds
53 tests, 2 failures, 45 skipped

1 个答案:

答案 0 :(得分:2)

由于您在_id名称的末尾有user_id(例如belongs_to),因此Ecto认为该关联称为user_id且数据库字段为{{1 }}。这就是为什么错误消息显示user_id_id是一个关联,并希望您使用user_id。您需要从所有关联名称中删除cast_assoc后缀,因为我假设数据库字段最后只有一个_id

_id