2016-01-18 26 views
3
** (Ecto.ConstraintError) constraint error when attempting to insert model: 

    * foreign_key: matches_person_id_fkey 

這裏是我的架構和遷移:這是什麼Ecto約束錯誤試圖告訴我?

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(變更)時,我使用的是變更:

%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 

回答

7

此錯誤是告訴你,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?

相關問題