我有Category
和Product
属于category_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
网络/ router.ex
[...]
scope "/", Shop do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
resources "/categories", CategoryController
resources "/products", ProductController
end
[...]
网络/模型/ 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
我想在新表单中为产品呈现下拉选择字段。这样用户就可以按类别名称选择产品的类别。目前,用户只能输入category_id:
网络/模板/产品/ 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>
[...]
我需要更改什么才能创建一个下拉选择字段,该字段按名称显示数据库中的所有类别?
答案 0 :(得分:1)
我会以可以直接传递到模板中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 %>