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'seachmethod always returns the original collection (your full@category.productsarray) 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
相关产品推荐
相关产品推荐

