【发布时间】:2026-02-10 23:35:02
【问题描述】:
我在 Phoenix 控制器中有一个查询,它获取一个学生列表,并且对于列表中的每一行,都会在其 id 上与血型进行连接并获取血型名称。我想在我生成但出现错误的 eex 模板中显示它。
这是学生模式:
schema "students" do
field :firstname, :string
field :lastname, :string
field :birthday, Ecto.Date
field :joined_on, Ecto.Date
field :bloodgroup_id, :integer
timestamps()
end
这是血型模型:
schema "bloodgroups" do
field :name, :string
timestamps()
end
我正在像这样在控制器中获取数据:
def query do
query = from s in Student,
join: b in BloodGroup, on: s.bloodgroup_id == b.id,
select: [s.firstname, s.lastname, s.birthday, s.joined_on, s.bloodgroup_id, b.name]
end
def index(conn, _params) do
students = Repo.all(query)
render(conn, "index.html", student_info: students)
end
并像这样在模板中显示:
<%= for student <- @student_info do %>
<tr>
<td><%= Enum.fetch(student, 0) %></td>
<td><%= student[:lastname] %></td>
<td><%= student[:birthday] %></td>
<td><%= student[:joined_on] %></td>
<td><%= student[:name] %></td>
<td class="text-right">
<%= link "Show", to: student_path(@conn, :show, student), class: "btn btn-default btn-xs" %>
<%= link "Edit", to: student_path(@conn, :edit, student), class: "btn btn-default btn-xs" %>
<%= link "Delete", to: student_path(@conn, :delete, student), method: :delete, data: [confirm: "Are you sure?"], class: "btn btn-danger btn-xs" %>
</td>
</tr>
<% end %>
但是使用Enum.fetch 和student[:firstname] 的形式不起作用并抛出Argument error 或protocol Phoenix.HTML.Safe not implemented
我想在模板中显示从控制器发送的内容,但遇到了这些错误。有一个更好的方法吗?我是 Phoenix 和 Elixir 的新手。
【问题讨论】:
标签: elixir phoenix-framework ecto