に特定の制約エラーの処理私はフィールドのいずれかに一意制約を持つチェンジがあります。コントローラの一フェニックス
defmodule Oauth.Shop do
use Ecto.Model
import Ecto.Changeset
alias Ecto.Changeset
schema "shops" do
field :shop, :string
field :access_token, :string
field :scope, :string
field :active, :boolean
timestamps
end
def changeset(shop, params \\ %{}) do
shop
|> cast(params, [:shop, :access_token, :scope, :active])
|> Changeset.validate_required([:shop, :access_token, :scope, :active])
|> unique_constraint(:shop)
end
end
を、私は新しいお店を挿入します。重複したお店が作成されている場合は、例外が発生します。%ショップが変数ながら、構造体であることを
def save_shop({:ok, access_params}, shop) do
Repo.insert(%Shop{shop: shop, access_token: access_params.access_token, scope: access_params.scope})
hook_uninstall(shop, access_params.access_token)
{:ok}
end
注:
** (exit) an exception was raised:
** (Ecto.ConstraintError) constraint error when attempting to insert model:
* unique: shops_shop_index
ここで私はレコードを保存コードがありますshopはクエリ文字列パラメータからの単なる値です。
Ecto.ConstraintErrorのプラグを作成することはできますが、詳細なユーザーのフィードバックに必要な細かい制御はできません。
例外をキャッチし、ショップが既に登録されていることをユーザーに通知する良い方法はありますか?
はどのようにあなたがDBに挿入されています。また、可能な場合代わりに
.field
を使用してマップのフィールドへのアクセスのパターンマッチングを使用することがより慣用的と考えられていますか?あなたは 'Repo.insert!'や 'Repo.insert'を使っていますか? [docs](https://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3)によれば、後者は簡単にパターンマッチすることができる2つのタプル '{:error、changeset}'を返すべきですon –'Changeset'を構造体ではなく' Repo.insert'に渡していますか? – Dogbert
@Dogbert et al。 。 。 Repo.insert()を含む質問が更新されました。 – sheldonkreger