0

I'm just following some rails tutorials, and built a basic CRUD app (a blog with comment system). My problem is that when I loop through each comment for a post, an annoying dump of the records is displayed after the each loop. It looks like there is some inspect dump, but I can't find the reason for this. Here is the code for the loop:

<h3>Comments</h3>
<%= @post.comments.each do |comment| %>
<div class="well">
  <p><strong><%= comment.username %></strong>: <%= comment.body %></p>
</div>
<%= link_to "[X]", [comment.post, comment], method: :delete, data: {confirm: 'Are you sure?'}, :class => 'btn btn-danger' %>
<hr>
<% end %>

Here is also the comment controller:

class CommentsController < ApplicationController


  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comment_params)
    redirect_to post_path(@post)
  end

  private def comment_params
    params.require(:comment).permit(:username, :body)
  end
  def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
  end


end

And here is a screenshot:

Ruby on rails each problem

Many thanks in advance for your help

Paul Massendari
  • 417
  • 3
  • 6

2 Answers2

2

It's the Enumerable returned by the each method. Change

<%= @post.comments.each do |comment| %>

to

<% @post.comments.each do |comment| %>

just because you don't want to see that

Ursus
  • 29,643
  • 3
  • 33
  • 50
1

What's happening here is that you're using <%= %>, which is the ERB tag that evaluates its content as Ruby and then prints it to the page. But you don't want to print out the value of @post.comments.each do |comment|; you just want to evaluate it. That's what the <% %> tag (no =) is for.

The reason you're seeing the text you are is that <%= %> implicitly calls to_s on its content.

This answer has a full list of ERB tag types: https://stackoverflow.com/a/7996827/882025

hoffm
  • 2,386
  • 23
  • 36