Select 字段可能有 belongs_to 个值

Select field with possible belongs_to values

我有 CategoryProduct 哪个 belongs_to 类别。设置:

mix phoenix.new shop
cd shop
mix ecto.create
mix phoenix.gen.html Category categories name
mix phoenix.gen.html Product products name category_id:integer
mix ecto.migrate

web/router.ex

[...]
scope "/", Shop do
  pipe_through :browser # Use the default browser stack

  get "/", PageController, :index
  resources "/categories", CategoryController
  resources "/products", ProductController
end
[...]

web/models/product.ex

defmodule Shop.Product do
  use Shop.Web, :model

  schema "products" do
    field :name, :string
    belongs_to :category, Vutuv.Category

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \ %{}) do
    struct
    |> cast(params, [:name, :category_id])
    |> validate_required([:name, :category_id])
  end
end

问题

我想在新的产品表单中呈现下拉 select 字段。这样用户就可以通过类别名称 select 产品类别。目前用户只能输入category_id:

web/templates/product/form.html.eex

[...]
<div class="form-group">
  <%= label f, :category_id, class: "control-label" %>
  <%= number_input f, :category_id, class: "form-control" %>
  <%= error_tag f, :category_id %>
</div>
[...]

我需要更改什么来创建一个下拉 select 字段,按名称显示数据库中的所有类别?

我会以一种可以直接传递给模板中 Phoenix.HTML.Form.select/4 的格式获取类别:

...
categories = Repo.all(from(c in Category, select: {c.name, c.id}))
render "...", categories: categories

然后在模板中将categories传给Phoenix.HTML.Form.select/4

<%= select f, :category_id, @categories %>