当不需要时显示模型的哈希

问题描述 投票:0回答:2

我正在为Ruby on Rails上的演示文稿申请注册。因此,我创建了几个模型,包括学生和管理模型。我将这些模型中的数据显示在一个带有引导程序的表中,如下所示:

<table class="table">
  <thead>
    <tr>
      <th scope="col">First name</th>
      # ...
    </tr>
  </thead>
  <tbody>
  <%= @student.each do |stud| %>
    <tr>
      <td scope="row"><%= stud.Firstname %></td>
      # ...
    </tr>
  <% end %>
</tbody>

我的控制器:

def list
  @student = Student.all.order(:Firstname)
end

问题是app会将数据库中所有对象的列表打印为哈希。

#<Presentation id: 3, Name: "Elon Musk", Year: "6 Gc", Title: "Electric Cars", Subject: "Phsics", Mentor: "Alberto Maraffio", Room: "N364", From: "13:45", Until: "14:00", Date: "07.11.18", Free: 5, Occupied: 0, Visitors: nil, created_at: "...", updated_at: "...">, #<Presentation id: 3, # ...

这不在layouts / application.html.erb文件中,我可以让它消失的唯一方法是注释掉<%= yield %>,当然,它也隐藏了页面的其余部分。我究竟做错了什么?

html ruby-on-rails ruby erb
2个回答
4
投票

这条线

<%= @student.each do |stud| %>

不应该显示在页面中。搬去

<% @student.each do |stud| %>

除此之外,我无法理解你想用这条线做什么

@student.each = Student.all.order(:Firstname)

它可能应该是

@student = Student.order(:Firstname)

并注意@students如何成为这个变量的更好名称


2
投票
def list
  @student.each = Student.all.order(:Firstname)
end

这对我来说很奇怪!

它应该是这样的:

def list
  @students = Student.order(:Firstname)
end

然后您的HTML也应该像:

<table class="table">
  <thead>
    <tr>
      <th scope="col">First name</th>
      # ...
    </tr>
  </thead>
  <tbody>
  <% @students.each do |stud| %>
    <tr>
      <td scope="row"><%= stud.Firstname %></td>
      # ...
    </tr>
  <% end %>
</tbody>
© www.soinside.com 2019 - 2024. All rights reserved.