【发布时间】:2016-07-20 00:41:22
【问题描述】:
我目前正在研究 Programming Phoenix 中的代码,但遇到了一个令我困惑的错误。
运行Rumbl.TestHelpers.insert_user时出现以下错误
** (Ecto.InvalidChangesetError) could not perform insert because changeset is invalid.
* Changeset changes
%{name: "Some user", password: "supersecret", password_hash: "$2b$12$ZaSx6WcTZnrRGrneHsrNF.oMx8if3yMNssnx1B/lGBD5/GPj17Ym6", username: "user50853EBB5B75FC40"}
* Changeset params
%{"name" => "Some user", "password" => "supersecret", "username" => "user50853EBB5B75FC40"}
* Changeset errors
[videos: "is invalid"]
(ecto) lib/ecto/repo/schema.ex:121: Ecto.Repo.Schema.insert!/4
Rumbl.TestHelpers.insert_user 看起来像这样:
alias Rumbl.Repo
def insert_user(attrs \\ %{}) do
changes = Dict.merge(%{
name: "Some user",
username: "user#{Base.encode16(:crypto.rand_bytes(8))}",
password: "supersecret"
}, attrs)
%Rumbl.User{}
|> Rumbl.User.registration_changeset(changes)
|> Repo.insert!()
end
Rumbl.User:
defmodule Rumbl.User do
use Rumbl.Web, :model
schema "users" do
field :name, :string
field :username, :string
field :password, :string, virtual: true
field :password_hash, :string
has_many :videos, Rumbl.Video
timestamps
end
def changeset(model, params \\ :invalid) do
model
|> cast(params, ~w(name username), [])
|> validate_length(:username, min: 1, max: 20)
|> unique_constraint(:username)
end
def registration_changeset(model, params) do
model
|> changeset(params)
|> cast(params, ~w(password), [])
|> validate_length(:password, min: 6, max: 100)
|> put_pass_hash()
end
defp put_pass_hash(changeset) do
case changeset do
%Ecto.Changeset{valid?: true, changes: %{password: pass}} ->
put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(pass))
_ -> changeset
end
end
end
最后是Rumbl.Video:
defmodule Rumbl.Video do
use Rumbl.Web, :model
schema "videos" do
field :url, :string
field :title, :string
field :description, :string
belongs_to :user, Rumbl.User
belongs_to :category, Rumbl.Category
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:url, :title, :description], [:category_id])
|> validate_required([:url, :title, :description])
|> assoc_constraint(:category)
end
end
我非常感谢任何能够阐明我为什么会出现此错误的人。
【问题讨论】:
-
你用什么参数调用
insert_user? -
@Dogbert 无,只是默认值。
-
您在某处传入 :videos 密钥,该密钥在创建用户时无效。你需要搜索它。另外作为旁注,Dict 已被弃用,取而代之的是 Map。
标签: elixir phoenix-framework ecto