elixir - => 和 : in an Elixir map? 有什么区别

标签 elixir phoenix-framework

在 Phoenix 框架中

def show(conn, %{"id" => id}) do
  json conn, Repo.get(User, id)
end

匹配良好,但使用 :符号与模式不匹配
def show(conn, %{"id": id}) do
  json conn, Repo.get(User, id)
end

当我从测试中调用以下代码时
conn
|> get(user_path(conn, :show, user.id))
|> json_response(200)

最佳答案

%{key: value}Atom 的简写键,而不是 String键。 让我们澄清一些事情:

:"a" == "a"
# => false

:"a" == :a
# => true

%{:a => 1} == %{"a": 1}
# => true

所以当你写 %{"id": id} ,意思是:%{id: id}这是 不是 %{"id" => id} ,并且由于您的参数映射没有 :id关键,它不匹配。

作为旁注,我实际上写了一个 Plug在 Phoenix Controller 中使用原子键来保持参数匹配简短。

关于elixir - => 和 : in an Elixir map? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025466/

相关文章:

testing - 使用 IEx 调试 phoenix 测试

enums - 为什么在 Enum.each 中设置的变量没有保存?

elixir - 条件和模式与 map 匹配

postgresql - (UndefinedFunctionError) 未定义函数 List.Chars.to_charlist/1

postgresql - Docker 错误 : standard_init_linux. go:185: exec 用户进程导致 "no such file or directory"

未安装 Elixir

elixir - 我应该在 Controller 或模型中为 Elixir Phoenix 使用 Ecto.Repo 吗?

elixir - 元组应该传递给宏吗?

elixir - Phoenix/Elixir 中的远程响应流程

elixir - 如何覆盖 Phoenix 中的错误?