为什么这个 rails 视图会在 .each do 循环结束时吐出一个原始数组? [英] Why is this rails view spitting out a raw array at the end of an .each do loop?

查看:25
本文介绍了为什么这个 rails 视图会在 .each do 循环结束时吐出一个原始数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被 Rails 视图中这个奇怪的输出难住了.这是我的模型:

I am stumped by this strange output in my Rails view. Here is my model:

class Comment < ActiveRecord::Base
  belongs_to :post
end

这是我观点的相关部分.我已将问题与此代码块隔离开来,特别是在最后一次迭代之后和循环结束之前发生的任何事情 <% end %>.如果我注释掉每次迭代中打印的实际文本,原始数组仍会打印.

Here is the relevant part of my view. I have isolated the problem to this block of code, specifically whatever happens after the last iteration and before the very end of the loop <% end %>. If I comment out the actual text printed in each iteration, the raw array still prints.

<h2>Comments</h2>
  <%= @post.comments.each do |comment| %>
    <p>
      <strong>Commenter:</strong>
      <%= comment.commenter %>
    </p>
    <p>
      <%= comment.body %>
    </p>
  <% end %> 

这是奇怪的输出(带样本评论.):

Here is the strange output (w/ sample comments.):

评论者:迈克尔

好帖子.

评论者:迈克尔

好帖子.

评论者:迈克尔

测试.

评论者:约翰

数组还在打印有趣吗?

 [#<Comment id: 1, commenter:
 "Michael", body: "Good post.",
 post_id: 1, created_at: "2011-01-12
 03:51:20", updated_at: "2011-01-12
 03:51:20">, #<Comment id: 2,
 commenter: "Michael", body: "Good
 post.", post_id: 1, created_at:
 "2011-01-12 03:52:06", updated_at:
 "2011-01-12 03:52:06">, #<Comment id:
 3, commenter: "Michael", body:
 "Test.", post_id: 1, created_at:
 "2011-01-12 03:52:24", updated_at:
 "2011-01-12 03:52:24">, #<Comment id:
 4, commenter: "John", body: "Is the
 array still printing funny?", post_id:
 1, created_at: "2011-01-12 03:57:20",
 updated_at: "2011-01-12 03:57:20">]

最后,这里是开发日志的读取方式.他们都是这个样子.

Finally, here is how the development log is reading. They all look like this.

Started GET "/posts/1" for 127.0.0.1 at 2011-01-11 22:01:52 -0600
  Processing by PostsController#show as HTML
  Parameters: {"id"=>"1"}
  [1m[36mPost Load (0.1ms)[0m  [1mSELECT "posts".* FROM "posts" WHERE ("posts"."id" = 1) LIMIT 1[0m
  [1m[35mComment Load (0.3ms)[0m  SELECT "comments".* FROM "comments" WHERE ("comments".post_id = 1)
Rendered posts/show.html.erb within layouts/application (57.5ms)
Completed 200 OK in 73ms (Views: 61.1ms | ActiveRecord: 0.4ms)

有人知道这是什么原因吗?如果这是 PHP,我想我会在代码中的某处留下一个 print_r.但事实并非如此,我也没有这样做.

Does anybody know what is causing this? If this were PHP, I'd guess I left a print_r somewhere in the code. But it isn't and I didn't do anything like that.

推荐答案

尝试删除 <%= @post.comments.each do |comment| 中的等号%>.只有当方法本身输出一些东西时才需要等号.在这种情况下,您只是使用它来迭代集合.

Try removing the equals sign in <%= @post.comments.each do |comment| %>. The equals is only necessary if the method itself outputs something. In this case you're just using it to iterate a collection.

这篇关于为什么这个 rails 视图会在 .each do 循环结束时吐出一个原始数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆