【问题标题】:How to show all records of a model in Phoenix select field如何在凤凰选择字段中显示模型的所有记录
【发布时间】:2023-03-21 04:20:01
【问题描述】:

我有以下型号...

  1. Page
  2. Category

我在page_controller.exnew 操作中有以下代码

def new(conn, _params) do
  changeset = Page.changeset(%Page{})
  categories = Repo.all(Category)
  render(conn, "new.html", changeset: changeset, categories: categories)
end

我在 page/new.html.eex 中有以下选择字段的代码

<div class="form-group">
  <%= label f, :category_id, "Parent", class: "control-label" %>
  <%= select f, :category_id, @categories ,class: "form-control" %>
</div>

它应该在选择字段中显示所有类别,以便我可以为页面选择一个类别,但不幸的是我无法找到问题。如果您有任何建议,请告诉我。

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    select/4 函数需要一个用于第三个参数的元组列表。

    来自文档:

    值应该是包含两项元组(如地图和关键字列表)的 Enumerable 或任何 Enumerable,其中元素将用作生成的选择的键和值。

    尝试将您的控制器更改为:

    categories = Repo.all(Category) |> Enum.map(&{&1.name, &1.id})
    

    这也可以在查询级别完成:

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

    请参阅Phoenix: Ordering a query set,了解在模型中将查询定义为函数的说明。

    【讨论】:

    • 您总是非常乐于助人...非常感谢。你知道,我开始制作应用程序只是因为我知道我会从 elixir 社区,特别是你那里得到及时的帮助。
    • 顺便问一下,我如何在模板中打印page.category.name
    • 这个&amp;({ &amp;1.name, &amp;1.id} 为我呈现正确的格式。
    • @Murtza 如果您有belongs_to 关联,那么您可以执行&lt;%= page.category.name %&gt; 确保您执行category = Repo.get(Page, id) |&gt; Repo.preload(:category) 以确保关联已加载。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2015-04-24
    • 2013-08-26
    相关资源
    最近更新 更多