【发布时间】:2017-03-16 16:16:04
【问题描述】:
我有 Category 和 Product 属于_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
问题
我想在产品的新表单中呈现一个下拉选择字段。以便用户可以通过类别名称为产品选择类别。目前用户只能输入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>
[...]
创建一个下拉选择字段,按名称显示数据库中的所有类别,我需要更改什么?
【问题讨论】:
标签: elixir phoenix-framework ecto