How to stop this array of attributes from showing

2019-09-10 07:49发布

问题:

This question already has an answer here:

  • What is the difference between <%, <%=, <%# and -%> in ERB in Rails? 7 answers

I have an annoying problem where my view keeps displaying an array of my object's attributes! My submenu is suppose to show categories in a tree form, which works, but it also shows this annoying array!

[ <#Category id: 26, title: "subtest", description: "a test within a test, testception", created_at: "2015-03-01 03:15:29", updated_at: "2015-03-03 01:08:09", ancestry: "6/24">]

[ <#Category id: 24, title: "Test", description: "No not be alarmed, this is only a test.", created_at: "2015-03-01 02:06:35", updated_at: "2015-03-03 01:07:52", ancestry: "6">]

I definately don't want the user to see this. How do I get rid of it??

Show.html.erb view:

<div id="submenu">
  <%= render 'submenu_cats', categories: @category.root.children %>
</div>

_submenu cats partial:

<ul>
  <%= categories.each do |category| %>
    <li>
        <%= link_to_unless_current category.title, category_path %>
        <%= render 'submenu_cats', categories: category.children if category.children.present? %>
    </li>
  <% end %>

Using: Rails 4.2, Ruby 2.1.5, Ancestry Gem

回答1:

Don't use...

<%= categories.each do |category| %>

Use

<% categories.each do |category| %>

When you use <%=, you're outputting the result of the expression. The result of categories.each is categories, the array that is being output. You don't want to output it, so use <% to evaluate the Ruby without outputting the results.



回答2:

You are using <%= %> which means that you are outputting the results of a Ruby code, instead use <% %> to executes the ruby code within the brackets.

So change

<%= categories.each do |category| %>

To

<% categories.each do |category| %>

Hope this help. :)