In the Phoenix framework
def show(conn, %{"id" => id}) do
json conn, Repo.get(User, id)
end
matches fine, but using the : notation does not pattern match
def show(conn, %{"id": id}) do
json conn, Repo.get(User, id)
end
when I call the following code from a test
conn
|> get(user_path(conn, :show, user.id))
|> json_response(200)
%{key: value} is a short-hand for Atom keys, not String keys. Let's clear up a few things:
:"a" == "a"
# => false
:"a" == :a
# => true
%{:a => 1} == %{"a": 1}
# => true
So when you write %{"id": id}, it means: %{id: id} which is not %{"id" => id}, and since your params map does not have an :id key, it does not match.
As a side note, I actually wrote a Plug to use atom keys in Phoenix controllers to keep params matching short and sweet.
When you use : the key is an atom. When you use => the key is whatever the type actually is. %{key: val} is actually just sugar for %{:key => val}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With