【发布时间】:2016-08-25 23:54:21
【问题描述】:
** (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
【问题讨论】:
标签: elixir phoenix-framework ecto