Search code examples
enumselixirphoenix-frameworkecto

In Elixir/Phoenix, what is the correct/best way to iterate through an EctoEnum.Postgres for a select input?


We have the following enum:

defmodule PricingEngine.Pricing.ProductCategoryEnum do
  use EctoEnum.Postgres,
      type: :product_category,
      enums: [
        :shoes,
        :apparel,
        :accessories
      ]
end

In a form.html.eex template, we would like to make a selection corresponding to this enum.

Currently, we have the following code:

<%= label f, :product_category %>
<%= select f, :product_category, PricingEngine.Pricing.ProductCategoryEnum.__enums__ %>
<%= error_tag f, :product_category %>

This works, but __enums__ suggests to me that this should be treated as a private property and not consumed in our code.

Is there a better way to do this?


Solution

  • The rest of the team also decided __enums_ looks like it shouldn't be used. Our couch suggested we should extract the list, like:

    defmodule PricingEngine.Pricing.ProductCategoryEnum do
      @options [
            :shoes,
            :apparel,
            :accessories
          ]
      use EctoEnum.Postgres,
          type: :product_category,
          enums: @options
    
       def values, do: @options
    end