我目前正在学习 Ruby on Rails,遵循这个特定的教程 https://www.youtube.com/watch?v=fmyvWz5TUWg&t=2625s
执行命令
rails g scaffold friends name:string email:string phone:string
和 rails db:migrate
后,我最终得到了这个简单朋友模型的 CRUD 结构(姓名、电子邮件和电话所有字符串)。
一切都很好,一切都很好,除了当我去
http://localhost:3000/friends
并且朋友列表以一种奇怪的方式显示时!我期待一张表格,其中每一行都是一个朋友,而不是我最终得到一个垂直结构,其中每个朋友都垂直显示......
index.html.erb
<p style="color: green"><%= notice %></p>
<h1>Friends</h1>
<div id="friends">
<% @friends.each do |friend| %>
<%= render friend %>
<p>
<%= link_to "Show this friend", friend %>
</p>
<% end %>
</div>
<%= link_to "New friend", new_friend_path %>
_friend.html.erb
<div id="<%= dom_id friend %>">
<p>
<strong>Name:</strong>
<%= friend.name %>
</p>
<p>
<strong>Email:</strong>
<%= friend.email %>
</p>
<p>
<strong>Phone:</strong>
<%= friend.phone %>
</p>
</div>
我相信我的配置有误,但无法找出是什么。
我遇到了同样的问题,在寻找解决方案时遇到了你的问题。 Rails 团队似乎决定更改索引模板,但我不知道原因是什么。可能是因为很多人想要定义自己的特定表格布局方式。
自定义脚手架模板
如果您确实想使用脚手架,并且不想每次都更改生成的索引,则可以创建自己的自定义脚手架模板。
自定义模板说明
这个人很好地解释了如何做到这一点:
https://web-crunch.com/posts/how-to-create-custom-scaffold-templates-in-ruby-on-rails
默认模板
您可能想查看默认模板作为参考。您可以在 Rails 安装中找到它们。我在 Windows 上运行,所以对我来说,它们位于:
C:\Ruby31-x64\lib uby\gems .1.0\gems ailties-7.0.3.1\lib ails\发电机 rb\脚手架模板
每个平台上的文件夹结构都是相似的。
GitHub 上的默认模板
您还可以查看 GitHub 上的源代码。在这里找到:
https://github.com/rails/rails/tree/main/railties/lib/rails/generators/erb/scaffold/templates
如果您具体查看“index.html.erb.tt”,您可以进入历史记录并查看它与呈现为表格相比发生了哪些变化。看起来模板的“现代化”更改发生在 2021 年 2 月 4 日。如果您查看之前的版本,您应该拥有可以生成表格的东西。
另一个教程
这是另一个示例,它生成使用 Bootstrap 和 Simple Form 的模板。我发现它非常适合,因为我已经在使用 Bootstrap,只需将简单表单添加到我的 Gemfile 中即可:
gem 'simple_form'
再生支架
从上面的示例中获取模板后,我想使用它们来重新生成我的视图。这可以通过以下方式完成:
rails g erb:scaffold friend first_name last_name phone twitter
免责声明
我昨天第一次真正了解了 Ruby,所以这个答案可能需要一些编辑。 :)
你的情况下,后端一切都好 - 唯一需要改进的部分是朋友的前端呈现。我不确定您使用的 Rails 版本 - 以及配置设置 - 因此有时脚手架可以生成表格 - 有时只是像您一样的简单视图。
为了在表格中显示好友,您必须实现 HTML 表格:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @friends.each do |friend| %>
<tr>
<td><%= friend.name %></td>
<td><%= friend.email %></td>
<td><%= link_to 'Show', friend %></td>
<td><%= link_to 'Edit', edit_friend_path(friend) %></td>
<td><%= link_to 'Destroy', friend, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>