AdamG AdamG - 7 months ago 12
Ruby Question

Rails table data shows as a hash under the real table data in Browser

I am trying to display all of the blog posts on the index page, but whenever I go to it, it displays what I want, and then below it, it puts the rest of the data as a hash. I want the first post and first description to be in the browser but I don't want the hash under it to be in there.
Screenshot of how the data from the table shows up

This is my posts_controller.rb

class PostsController < ApplicationController

def index
@post = Post.all
end

def show
@post = Post.find(params[:id])
end

def new
@post = Post.new(params[:id])
end

def create
@post = Post.new(post_params)

@post.save
redirect_to @post
end
end

private
def post_params
params.require(:post).permit(:title, :description)
end


This is my index.html.erb file

<h1>Blog Posts</h1>

<table>
<th>Title</th>
<th>Description</th>
<div><%= @post.each do |post| %></div>
<tr>
<td><%= post.title %></td>
<td><%= post.description %></td>
</tr>
</table>
<% end %>


Any help would be greatly appreciated!

Answer

I believe you will find that this line is the source of your issue:

<div><%= @post.each do |post| %></div>

The <%= %> tag in ERB is for outputting the results of the evaluation. You want to just process the loop, for which you use the <% %> tag.

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

Note the removal of the = sign as well as the <div>s. You don't need the <div> tags since nothing should be output from iterating code.

Also, your HTML is not valid - div can't be a direct child of table. Use like:

<table>
  <thead>
    <th>Title</th>
    <th>Description</th>
  </thead>
  <tbody>
    <% @post.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.description %></td>
      </tr>
    <% end %>
  </tbody>
</table>