使用 Ecto 2.0:
defmodule PlexServer.BoardInstanceTest do
use PlexServer.ModelCase
alias PlexServer.BoardInstance
@valid_attrs %{board_pieces: [%PlexServer.BoardTileInstance{x: 0, y: 0}], empire: %PlexServer.EmpireInstance{}}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = BoardInstance.changeset(%BoardInstance{}, @valid_attrs)
assert changeset.valid?
end
end
defmodule PlexServer.BoardInstance do
use PlexServer.Web, :model
alias PlexServer.BoardTileInstance
schema "board_instances" do
belongs_to :empire, PlexServer.EmpireInstance
has_many :board_pieces, BoardTileInstance
timestamps
end
@required_fields ~w()
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_assoc(:board_pieces, required: true)
|> cast_assoc(:empire, require: true)
end
end
我的测试失败了
** (RuntimeError) 不支持使用 cast/3 转换关联,请改用 cast_assoc/3
查看文档是说 cast_assoc/3 需要在 cast/3 之后调用,所以我很确定我错过了使该测试正常工作所必需的一些东西。
编辑:更新了我的代码,现在收到一个新错误:
** (Ecto.CastError) 期望参数是一张地图,得到:
%PlexServer.BoardTileInstance{__meta__: #Ecto.Schema.Metadata<:built>, fleets: #Ecto.Association.NotLoaded<association :fleets is not loaded>, id: nil, inserted_at: nil, system: #Ecto.Association.NotLoaded<association :system is not loaded>, updated_at: nil, x: 0, y: 0}
我猜我的@valid_attrs 格式不正确?