How do I iterate over an array created from a phx generator

On phoenix 1.7.7, when generating a Tests Test tests tags:array:integer the generator creates a proper array

    create table(:tests) do
      add :tags, {:array, :integer}

However, when inserting the values from the ready-made CRUD

          options={[{"1", 1}, {"2", 2}]}

Array is not showing (or is it??) correctly

In PostgreSQL:

id | tags  |       
  1 | {1}   | 
  4 | {1,2} | 

Looking in the table showing content:

  row_click={fn {_id, test} -> JS.navigate(~p"/tests/#{test}") end}
  <:col :let={{_id, test}} label="Tags"><%= test.tags %></:col>
  <:action :let={{_id, test}}>
    <div class="sr-only">
      <.link navigate={~p"/tests/#{test}"}>Show</.link>
    <.link patch={~p"/tests/#{test}/edit"}>Edit</.link>
  <:action :let={{id, test}}>
      phx-click={JS.push("delete", value: %{id:}) |> hide("##{id}")}
      data-confirm="Are you sure?"

<%= test.tags %> is the array. However, I cannot simply index that array, for example: test.tags[0] gives me the Access calls for keywords expect the key to be an atom, got: 0

What do you think? How to iterate over that array? I’ve seen Arrays — Arrays v2.1.0 and

{:array, :integer} is the Ecto Type for the database, but is represented in Elixir as a list (see Ecto: Primitive Types) and lists don’t support indexing.
You could use to access a specific element in a list.
If you want to iterate over a list you should checkout the other functions inside the Enum module.

Assuming you just want to show all tags, you could use the special :for attribute that HEEx supports.

  <:col :let={{_id, test}} label="Tags">
    <span :for={tag <- test.tags}><%= tag %></span>

source: Components and HEEx — Phoenix v1.7.7

1 Like