【问题标题】:Select field with possible belongs_to values选择具有可能的 belongs_to 值的字段
【发布时间】:2017-03-16 16:16:04
【问题描述】:

我有 CategoryProduct 属于_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


    【解决方案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 %>
    

    【讨论】:

    • 这是一个很好的答案。 FWIW ecto 文档表明您会这样做select(f, :cateogry_id, Enum.map(@categories, &amp;{&amp;1.name, &amp;1.id}))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 2020-06-03
    • 2021-03-09
    • 2012-02-17
    • 1970-01-01
    相关资源
    最近更新 更多