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

Hello,
On phoenix 1.7.7, when generating a phx.gen.live Tests Test tests tags:array:integer the generator creates a proper array

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

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

     <.input
          field={@form[:tags]}
          type="select"
          multiple
          label="Tags"
          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:

<.table
  id="tests"
  rows={@streams.tests}
  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>
    </div>
    <.link patch={~p"/tests/#{test}/edit"}>Edit</.link>
  </:action>
  <:action :let={{id, test}}>
    <.link
      phx-click={JS.push("delete", value: %{id: test.id}) |> hide("##{id}")}
      data-confirm="Are you sure?"
    >
      Delete
    </.link>
  </:action>
</.table>

<%= 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.1 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 Enum.at/2 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>
  </:col>

source: Components and HEEx — Phoenix v1.7.7

1 Like