gpt4 book ai didi

elixir - 无法识别 2 个字段上的 unique_constraint

转载 作者:行者123 更新时间:2023-12-04 11:35:50 25 4
gpt4 key购买 nike

我正在尝试在 Ecto Postgres 中做 2 个字段的唯一约束。到目前为止,我设法做到了:

在迁移中:

create unique_index(:presences, [:event_id, :user_id], name: :special_event_user)

变更集:
 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

也试过:
|> unique_constraint(: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 has not defined any constraint.

我以为我已经这样做了。有什么建议?

编辑:

行动:
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

当没有错误时,上面代码中的示例存在:
%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}

编辑:现在我得到:
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

最佳答案

你没有通过你的变更集功能。

presence =
%Presence{ user_id: result.id, event_id: val, state: Presence.get_assigned }
|> Repo.insert!

应该:
presence =
Presence.changeset(%Presence{}, %{user_id: result.id, event_id: val, state: Presence.get_assigned})
|> Repo.insert!

关于elixir - 无法识别 2 个字段上的 unique_constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com