Today I Learned

hashrocket A Hashrocket project

Phoenix Select Form Helper

The select form helper allows you to easily add a select input to your forms.

= form_for @changeset, resource_path(@conn, :create), fn f ->
  = select f, :book_id, @books
  = submit "Save Post", class: "btn"

Among the types of arguments that the select helper can accept are two-item tuples. The first item in the tuple is used as the label for the option and the second item is used as the value for the option.

Media.list_books returns a list of structs representing all of the books in the database. We'll need to get from a list of structs to a list of tuples.

To do that, we'll pipe the list of Book structs to Enum.map and use an anonymous function to generate two-value tuples from those structs.

def new(conn, _params)
  ...
  books =
    Media.list_books
      |> Enum.map(&{"#{&1.title} by #{&1.author}", &1.id})

  render conn, "new.html", changeset: changeset, books: books
end
See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.