I'am trying to do 2 fields unique constraint in Ecto Postgres. So far I managed to do:
In Migration:
create unique_index(:presences, [:event_id, :user_id], name: :special_event_user)
Changeset:
def changeset(presence, params \\ :empty) do
presence
|> cast(params, @required_fields, @optional_fields)
|> foreign_key_constraint(:user_id)
|> foreign_key_constraint(:event_id)
|> unique_constraint(:event_id, name: :special_event_user)
end
Have also tried:
|> unique_constraint(:special_event_user)
But I keep getting:
If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and define the proper
constraint name. The changeset has not defined any constraint.
Which I thought I already did. Any suggestions?
Edit:
Action:
def assign(conn, %{"event" => event_id}) do
case Integer.parse(event_id) do
{val, _ } ->
case Repo.one(User.unique_user(User, get_session(conn, :login))) do
nil -> conn
|> put_flash(:error, "Błąd bazy danych")
|> redirect(to: "/event")
result ->
presence = %Presence{ user_id: result.id, event_id: val, state: Presence.get_assigned } |> Repo.insert!
conn
|> put_flash(:info, "Zostałeś zapisany na wydarzenie")
|> redirect(to: "/event")
end
end
end
Egzample presence from above code when there is no error:
%Kpsz.Model.Presence{__meta__: #Ecto.Schema.Metadata<:loaded>,
event: #Ecto.Association.NotLoaded<association :event is not loaded>,
event_id: 1, id: 1, inserted_at: #Ecto.DateTime<2015-12-14T15:45:39Z>,
state: 1, updated_at: #Ecto.DateTime<2015-12-14T15:45:39Z>,
user: #Ecto.Association.NotLoaded<association :user is not loaded>, user_id: 1}
Edit: Now I'm getting:
constraint error when attempting to insert model:
* unique: special_event_user
If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and define the proper
constraint name. The changeset defined the following constraints:
* unique: presences_special_event_user_index
* foreign_key: presences_event_id_fkey
* foreign_key: presences_user_id_fkey
You are not going through your changeset function.
presence =
%Presence{ user_id: result.id, event_id: val, state: Presence.get_assigned }
|> Repo.insert!
Should be:
presence =
Presence.changeset(%Presence{}, %{user_id: result.id, event_id: val, state: Presence.get_assigned})
|> Repo.insert!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With