独特的索引约束在Phoenix应用程序中不起作用

Dav*_*mes 12 elixir phoenix-framework

在我的凤凰应用程序中,我的用户模型如下:

defmodule MyApp.User do
  use MyApp.Web, :model

  schema "users" do
    field :username, :string, unique: true
    field :email, :string, unique: true
    field :crypted_password, :string
    field :password, :string, virtual: true

    timestamps
  end

  @required_fields ~w(email password username)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> unique_constraint(:email)
    |> unique_constraint(:username)
    |> validate_format(:email, ~r/@/)
    |> validate_length(:password, min: 5)
  end
end
Run Code Online (Sandbox Code Playgroud)

我也有以下迁移:

defmodule MyApp.Repo.Migrations.CreateUser do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :email, :string
      add :username, :string
      add :crypted_password, :string

      timestamps
    end

    create unique_index(:users, [:email])
    create unique_index(:users, [:username])
  end
end
Run Code Online (Sandbox Code Playgroud)

我有registration_controller_ex以下内容:

defmodule MyApp.RegistrationController do
  use MyApp.Web, :controller
  alias MyApp.User

  def new(conn, _params) do
    changeset = User.changeset(%User{})
    render conn, changeset: changeset
  end

  def create(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{}, user_params)

    if changeset.valid? do
      user = MyApp.Registration.create(changeset, MyApp.Repo)
      conn
      |> put_flash(:info, "Your account was created")
      |> redirect(to: "/")
    else
      conn
      |> put_flash(:info, "Unable to create account")
      |> render("new.html", changeset: changeset)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

所以,尽管如此,我非常确定我usernameemailUser中的字段是唯一索引.我还通过调用unique_constraint验证User.changeset来确保它们是唯一的.但是,在我的界面中,我创建的用户使用与之前创建的用户相同的电子邮件和用户名,验证变更集并"创建"用户.(它实际上并没有创建,当我查看数据库时没有添加任何内容)

我在服务器日志上得到以下内容,但我的changeset.valid?是真的.

[debug] BEGIN [] OK query=139.3ms queue=8.2ms
[debug] INSERT INTO "users" ("crypted_password", "email", "inserted_at", "updated_at", "username") VALUES ($1, $2, $3, $4, $5) RETURNING "id" ["$2b$12$MN1YxFUGLMIJYXseZn0sjuuVs9U1jRdYtRr9D8XQsAqdh.D2sRRXa", "email@gmail.com", {{2015, 9, 30}, {11, 7, 25, 0}}, {{2015, 9, 30}, {11, 7, 25, 0}}, "username"] ERROR query=5.5ms
[debug] ROLLBACK [] OK query=0.4ms
Run Code Online (Sandbox Code Playgroud)

另外,我在User.changeset函数中查找的其他内容(例如最小密码长度和其他内容)会报告给用户,并且工作正常.它只是唯一的索引,:email并且:username未能报告.

Ger*_*der 17

unique_constraint会由数据库进行检查,因此只能在插入记录触发.调用changeset.valid?不会检查约束,因此在这种情况下返回true.您需要检查Repo插入的返回元组,并执行以下操作:

def create(conn, %{"user" => user_params}) do
  changeset = User.changeset(%User{}, user_params)
  case  MyApp.Repo.insert changeset do
    {:ok, changeset} -> 
      conn
      |> put_flash(:info, "Your account was created")
      |> redirect(to: "/")      
    {:error, changeset} ->
      conn
      |> put_flash(:info, "Unable to create account")
      |> render("new.html", changeset: changeset)      
  end
end
Run Code Online (Sandbox Code Playgroud)

现在你的changeset.errors内容丰富了,你应该能够获取错误changeset.errors[:email]