试图告诉我这个Ecto Constraint Error是什么?

时间:2016-01-18 14:55:52

标签: elixir phoenix-framework ecto

** (Ecto.ConstraintError) constraint error when attempting to insert model:

    * foreign_key: matches_person_id_fkey

这是我的架构和迁移:

def change do
  create table(:matches) do
    add :percentage, :float
    add :person_id, references(:persons)
    add :star_id, references(:stars)

    timestamps
  end
  create index(:matches, [:person_id])
end

schema "matches" do
  field :percentage, :float
  belongs_to :person, Person
  belongs_to :star, Star

  timestamps
end

我在调用Repo.insert(changeset)时使用的变更集是:

%Ecto.Changeset{action: nil,
 changes: %{percentage: 0.513657, person_id: 55, star_id: 1}, constraints: [],
 errors: [], filters: %{},
 model: %App.Match{__meta__: #ecto.Schema.Metadata<:built>, id: nil,
  inserted_at: nil, percentage: nil,
  person: #ecto.Association.NotLoaded<association :person is not loaded>,
  person_id: nil,
  star: #ecto.Association.NotLoaded<association :star is not loaded>,
  star_id: nil, updated_at: nil}, optional: [], opts: [],
 params: %{"percentage" => 0.513657, "person_id" => 55, "star_id" => 1},
 prepare: [], repo: nil, required: [:percentage, :person_id, :star_id],
 types: %{id: :id, inserted_at: Ecto.DateTime, percentage: :float,
   person_id: :id, star_id: :id, updated_at: Ecto.DateTime}, valid?: true,
 validations: []}

我不确定发生了什么,或者我是否在路上做了一些改变,因为这在以前是有效的。这个错误似乎暗示我需要一个person_id,我这样做。

编辑:根据要求,我正在进行匹配插入的函数调用

...
Repo.transaction(fn ->
  case Repo.insert(person_changeset) do
  {:ok, person} ->
     Match.create(person.id)
  {:error, _}
     Repo.rollback(:no_bueno)
  end
end)

def create(person_id) do
  ...
  params = %{"person_id" => person.id, "percentage" => percentage, "star_id" => star.id}
  changeset = __MODULE__.changeset(%__MODULE__{}, params)
  case Repo.insert(changeset) do
  {:ok, _person} ->
     IO.puts "success"
  {:error, _changeset} ->
     Repo.rollback(:no_bueno)
  end
end

1 个答案:

答案 0 :(得分:12)

此错误告诉您id为55的人不存在。

有些相关,在您的迁移中,不需要以下内容:

create index(:matches, [:person_id])

references/2

时,将自动创建索引
add :person_id, references(:persons)

如果您要填充变更集中的错误,则需要在变更集中添加foreign_key_constraint/3

cast(match, params, ~w(person_id), ~w())
|> foreign_key_constraint(:person_id)

虽然与问题没有直接关系,但您可能在模型中使用Repo。请参阅Should I use Ecto.Repo in Controller or Model for Elixir Phoenix?