postgresql - 使用 Ecto.Repo.update_all/3 插入 NULL 值

标签 postgresql elixir ecto

假设我们有一个名为 users 的表,其中有一个可为空的列 permission_set_id,它是另一个名为 permission_sets 的表的外键,通过以下方式实现Ecto.Schema.belongs_to/3(文档 here)宏。我需要用这样的查询使该字段无效:

query = from u in User,
        where: u.id == ^user_id

case Repo.update_all(query, set: [permission_set_id: nil]) do
  {1, _terms} -> send_resp(conn, :no_content, "")
  {0, _terms} -> send_resp(conn, :not_found, "User not found.")
end

但是这个单元测试失败了:

test "unassigns user's permission set", %{conn: conn} do
  user = Factory.insert(:user)
  permission_set = Factory.insert(:permission_set, user_id: user.id)
  tight_user = Factory.insert(:user, permission_set_id: permission_set.id)

  conn = delete conn, user_user_permission_set_path(conn, :delete, user)

  query = from u in User,
    where: u.id == ^tight_user.id,
    select: u.permission_set_id

  assert response(conn, 204)
  refute Repo.one(query)
end

结果

test unassigns user's permission set (SpheriumWebService.UserPermissionSetControllerTest)
test/controllers/user_permission_set_controller_test.exs:96

Expected false or nil, got 94
code: Repo.one(query)
stacktrace:
  test/controllers/user_permission_set_controller_test.exs:108: (test)

我尝试将值设置为 fragment("NULL"),发现我无法在那里使用它。值 :null:nilifyfalse 不起作用,表示无法将其转换为整数值。

有什么想法吗?我检查了tests , 但到目前为止没有发现任何接近的东西。

谢谢。

最佳答案

看起来像是测试中的一个简单错误。

您正在创建两个用户:

  • user(可能是工厂分配给它的权限)
  • tight_user(您明确分配权限的地方)
  • 删除用户的权限
  • 查询 tight_users 权限并期望它为 nil 而您从未删除它,因为您正在删除 user 权限。

关于postgresql - 使用 Ecto.Repo.update_all/3 插入 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581725/

相关文章:

python - python中的数据可视化——连接到数据库后

php - 有没有办法在 php 的一次调用中发送多个 postgresql sql 准备语句?

postgresql - 如何在 docker Alpine Linux 容器中运行 Postgres?

elixir - 将 LEFT OUTER JOIN 查询转换为 Ecto

database - 使用 Elixir 选择 Postgres ltree 的直接 child

postgresql - 更快地从大型 jsonb 字段中检索多个值(postgresql 9.4)

utf-8 - httpoison - 响应正文显示乱码文本而不是 html

药剂 : Writing Parameterized Function using & Notation

bash - Elixir ——分离的pid

elixir - 如何在 Elixir Ecto 中为列添加别名?