Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this rails view spitting out a raw array at the end of an .each do loop? [duplicate]

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

class Comment < ActiveRecord::Base
  belongs_to :post
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.):

Commenter: Michael

Good post.

Commenter: Michael

Good post.

Commenter: Michael

Test.

Commenter: John

Is the array still printing funny?

 [#<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)

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.

like image 282
Michael Avatar asked Jan 12 '11 04:01

Michael


1 Answers

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.

like image 171
Jimmy Avatar answered Nov 01 '22 09:11

Jimmy