When I use Ecto.Enum.values in a select/4 function, how to translate the values inside the ecto schema?
e.g.
field :animal, Ecto.Enum, values: [:cat: 1, :elephant: 2]
When I use Ecto.Enum.values in a select/4 function, how to translate the values inside the ecto schema?
e.g.
field :animal, Ecto.Enum, values: [:cat: 1, :elephant: 2]
Hi! I found this article that helped me to achive it Phoenix and Ecto Enum translations β Ricardo Marinovic Two first methods get the job done
@doc """
Translates an enum value using gettext.
"""
def translate_enum(value) when is_atom(value) do
value =
value
|> Atom.to_string()
Gettext.dgettext(ExampleWeb.Gettext, "enums", value)
end
@doc """
Returns all translated enum values for the select options.
"""
def translated_select_enums(module, field) do
module
|> Ecto.Enum.values(field)
|> Enum.map(fn value -> {translate_enum(value), value} end)
end
You can create your own module with this and youβre right on