You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails项目中show.html.erb页面意外输出数据库数组数据的解决求助

Fixing Unwanted Database Array Output in Rails ERB

Hey there! Let's sort out that unexpected array data showing up at the bottom of your page—it's a super common gotcha for Rails/HTML beginners, so don't stress about it!

What's Causing the Issue?

The root problem is how you're using ERB tags for your loops:

  • You’ve got <%= @category.products.each do |product| %> for both of your loops.
  • In ERB, <%= %> outputs the return value of the code inside it. Ruby's each method always returns the original collection (your full @category.products array) after finishing the loop, which is exactly what's ending up as that unwanted text at the bottom of your page.

The Simple Fix

All you need to do is swap those <%= tags for <% tags for your each loops. This tells ERB to run the loop logic without printing its return value. The <%= %> tags for individual product attributes (like product.id or product.name) are still perfect—you want those values to show up on the page!

Here's your corrected code:

<table>
  <tr>
    <th>Name</th>
  </tr>
  <% @category.products.each do |product| %>
    <tr>
      <td><%= product.id %></td>
      <td><%= product.size %></td>
      <td><%= product.name %></td>
    </tr>
  <% end %>
</table>

<% @category.products.each do |product| %>
  <h3><%= product.id %></h3>
  <h3><%= product.size %></h3>
  <h3><%= product.name %></h3>
<% end %>

That should completely remove those redundant array entries from your page. Happy coding!

内容的提问来源于stack exchange,提问作者Kirix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:47:42