I keep getting this error when I try to insert a record where I know the ticket does not already exist.
constraint error when attempting to insert struct:
* PRIMARY (unique_constraint)If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
callunique_constraint/3
on your changeset with the constraint
:name
as an option.The changeset defined the following constraints:
- unique_ticket (unique_constraint)
This is what my schema and changeset are defined as:
schema "tickets" do
field(:type, :integer, default: 1)
field(:ticket, :string)
field(:title, :string)
field(:body, :string)
belongs_to(:release, Ern.Pdata.Release)
end
def changeset(ticket, attrs) do
ticket
|> cast(attrs, [:release_id, :type, :ticket, :title, :body])
|> validate_required([:release_id, :type, :ticket, :title])
|> unique_constraint(:ticket, name: :unique_ticket)
end
I wouldn’t think this would be an issue but I’ll mention it anyway…
I manually defined the data structure in mySQL - I did NOT create a migration for the table so it doesn’t have a create unique_index()
to refer to.
Any clues where I’m going wrong???
UPDATE #1: I’m reading the error as; ecto is really complaining about my PRIMARY key which is defined as an auto-incrementing id field. I’ve never had to define a changeset “unique_constraint” for an id field before, so why now?? I thought ecto automagically deals with id fields by itself!?
UPDATE #2: I went ahead and added a constraint for the auto-incrementing id field |> unique_constraint(:id, name: :PRIMARY)
and that fixed my problem.
I’m still not understanding why, all of a sudden, ecto wants the unique constraint defined for the id field - I’ve built several other database apps using elixir and this is the first time it moaned at me about the table’s primary index (all my tables use auto-incrementing id fields)?
Thanks!