如何确保变更集可以模式匹配 Ecto Repo.Insert/1 的私有函数?

How to ensure that a changeset can pattern match Ecto Repo.Insert/1's private functions?

我第一次使用 Ecto 制作 Phoenix 博客,并且遇到 Repo 问题。insert/1。我得到的具体错误是:

no function clause matching in Ecto.Repo.Schema.metadata/1

我一直在研究 IEx.pry,发现我传递给 Repo.Insert 的变更集是有效的(有效:true),并且包含我想要的变更(变更:%{content :"bar",标题:"foo"})。但是,我看到 Repo.Schema.metadata/1 需要上下文和来源,我不确定 Repo.insert 或 Repo.do_insert 是否能够获取并添加它。我也不知道如何检查 Ecto 私有函数中变量的状态。

我的控制器代码:

def create(conn, %{"post" => post_params}) do
  changeset = Post.changeset(%Post{}, post_params)
  case Repo.insert(changeset) do #this line blows up
    {:ok, post} ->

我的型号代码:

defstruct [:id, :title, :date, :content, :active]

schema "posts" do
  field :title, :string
  field :date, Ecto.DateTime
  field :content, :string #is text in migration
  field :active, :boolean, default: false

  timestamps
end

@required_fields ~w(title content)
@optional_fields ~w(date)

def changeset(model, params \ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
end

谢谢!

这里的问题可能是 defstruct [:id, :title, :date, :content, :active] 行。您正在用自己的宏覆盖 schema 宏生成的结构。

删除它,您的代码应该可以工作。