W3cubDocs

/Phoenix

Phoenix.Param protocol

A protocol that converts data structures into URL parameters.

This protocol is used by URL helpers and other parts of the Phoenix stack. For example, when you write:

user_path(conn, :edit, @user)

Phoenix knows how to extract the :id from @user thanks to this protocol.

By default, Phoenix implements this protocol for integers, binaries, atoms, maps and structs. For maps and structs, a key :id is looked up.

Nil values cannot be converted to param.

Custom parameters

In order to customize the parameter for any model or struct, one can simply implement this protocol.

However, for convenience, this protocol can also be derivable. For example:

defmodule User do
  @derive Phoenix.Param
  defstruct [:id, :username]
end

By default, the derived implementation will also use the :id key. In case the user does not contain an :id key, the key can be specified with an option:

defmodule User do
  @derive {Phoenix.Param, key: :username}
  defstruct [:username]
end

will automatically use :username in URLs.

When using Ecto, you must call @derive before your schema call:

@derive {Phoenix.Param, key: :username}
schema "users" do

Summary

Types

t()

Functions

to_param(term)

Types

t :: term

Functions

to_param(term)

Specs

to_param(term) :: String.t

© 2014 Chris McCord
Licensed under the MIT License.
https://hexdocs.pm/phoenix/Phoenix.Param.html