Bitwise
Bitwise

Reputation: 8451

Map arguments in functions

I'm learning elixir and one thing I don't understand the style in which you see maps being arguments in function. The most common place you see this is in controllers like this:

CONTROLLER
def create(conn, %{"league" => league_params}) do
  league = %League{}
    |> League.changeset(league_params)
    |> Repo.insert()

  case league do
    {:ok, league} ->
      conn
      |> put_flash(:info, "League Created Successfully.")
      |> redirect(to: page_path(conn, :index))
    {:error, %Ecto.Changeset{} = changeset} ->
      render(conn, "new.html", changeset: changeset)
  end
end

So, the create/2 function. The second argument looks like this %{"league" => league_params}. Correct me if I'm wrong but that is a map, so why do we reference the value below League.changeset(league_params) instead of the key League.changeset("league")?

This may seem like a silly question but I can't figure this one out and I can't find docs for this question. Thanks for the help.

Upvotes: 4

Views: 2073

Answers (1)

Dogbert
Dogbert

Reputation: 222198

In a Map pattern, the keys are the values to match with a key of the map and the value is the pattern to bind the value of that key to. For example, the pattern %{"foo" => x} will successfully match against the map %{"foo" => 123} and as a result of the match, the variable x will be bound to 123.

Similarly, in your example, league_params will be bound to the value of params map's "league" key, which is why league_params is passed to the changeset. The code is almost equivalent to doing def create(conn, params) and then league_params = params["league"] in the body of the function. (Almost because if the value doesn't exist, the pattern match will fail but this code will set league_params to nil.)

Upvotes: 7

Related Questions