问题
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