Sorvah
Sorvah

Reputation: 333

Pattern matching a map within a map in the function header

I currently have a params instance that looks like this:

  params: %{
    "continent" => %{
      "deleted_date" => nil,
      "name" => "Asia",
      "to_be_deleted" => true
    },
    "id" => "16"
  },

I am trying to pattern match against the to_be_deleted key so that if it is true, a different version of update/2 will run, whilst also assigning the content of continents to continent_params

My current update/2:

  def update(conn, %{"id" => id, "continent" => continent_params}) do
    # stuff         
  end

My attempt to pattern match a different version:

  def update(conn, %{"id" => id, %{"to_be_deleted" = true} => continent_params}) do
    #stuff
  end

However this produces a syntax warning regarding a } that I can't clear. I'm unsure whether I am trying to do too much in the function header or whether I should be using a different syntax to access the 'map within the map'.

Upvotes: 2

Views: 108

Answers (1)

vahid abdi
vahid abdi

Reputation: 10318

Try it this way:

def update(conn, %{"id" => id, "continent" => %{"to_be_deleted" = true} = continent_params}) do
  #stuff                       ^
end

You forgot to pattern match against "continent" Key.

Upvotes: 4

Related Questions