Why is Rails displaying all the information on the page? [duplicate]

巧了我就是萌 提交于 2019-12-12 18:28:34

问题


I have the following code in my rails 3.2 app:

 <ul>            
          <% user_to_show.topics.each do |topic| %>
          <li> <%= link_to topic.name, topic %> 
              <ul>
                <%= topic.nodes.each do |node| %>
                  <li> <%= link_to node.title, node %> </li>
                <% end %>
              </ul>
          </li>
          <% end %>    
  </ul>

When I go to a user page, I would expect it to just display a link to each topic and the nodes in that topic. It does that, but then it also displays the actual data of each node at the end (see below). How come and how do I fix it?

Sample Topic  
node1  
node2 

[#<Node id: 1, title: "node1", intro_content: "sample content", user_id: 2, date_modified: nil, created_at: "2012-07-19.." [etc..] #<Node id: 2, title: "node2", intro_content: "sample 2 content..", user_id: 2, etc.. ]

回答1:


Because of this line:

<%= topic.nodes.each do |node| %>

Every Ruby statement is an expression. So every method returns something (even if it's nil). So if you call an "each", it will return the Array after the loop is done. So, as you used <%=, it will write this array after the loop is over.

You should have used:

<% topic.nodes.each do |node| %>


来源:https://stackoverflow.com/questions/11581570/why-is-rails-displaying-all-the-information-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!