unique_constraint无法识别2个字段

Hai*_*ito 7 elixir ecto phoenix-framework

我试图在Ecto Postgres做2场独特的约束.到目前为止,我设法做到了:

在迁移中:

create unique_index(:presences, [:event_id, :user_id], name: :special_event_user)
Run Code Online (Sandbox Code Playgroud)

变更:

 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
Run Code Online (Sandbox Code Playgroud)

也尝试过:

|> unique_constraint(:special_event_user)
Run Code Online (Sandbox Code Playgroud)

但我一直在:

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.
Run Code Online (Sandbox Code Playgroud)

我以为我已经做过了.有什么建议?

编辑:

行动:

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
Run Code Online (Sandbox Code Playgroud)

当没有错误时,从上面的代码中出现Egzample:

%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}
Run Code Online (Sandbox Code Playgroud)

编辑:现在我得到:

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
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 8

您没有完成更改集功能.

presence =
  %Presence{ user_id: result.id, event_id: val, state: Presence.get_assigned }
  |> Repo.insert!
Run Code Online (Sandbox Code Playgroud)

应该:

presence =
  Presence.changeset(%Presence{}, %{user_id: result.id, event_id: val, state: Presence.get_assigned})
  |> Repo.insert!
Run Code Online (Sandbox Code Playgroud)