Search code examples
htmlruby-on-railsruby-on-rails-4eachenumerable

Empty div is showing up with ruby .each enumerable on HTML.erb page.


I can't seem to figure out why my ruby .each enumerable is churning out an empty div if my array of objects is empty, or adding an empty div at the bottom if there is one object in my @posts variable.

Here is my index.html.erb page:

<div id="post_feed">
<%if @posts.any?%>
  <%@posts.each do |p|%>
    <div class="post_text_box">
      <%=p.body%>
    </div>
  <%end%>
<%end%>
</div>

Post Controller:

def index
    @posts = current_user.posts
    @new_post = current_user.posts.new 
  end

CSS:

#post_feed{
  margin-right:auto; 
  margin-left:auto; 
  width:400px; 
}

.post_text_box{
  padding:10px;
  margin:10px;
  background-color:#FFFFFF;
}

rails console shows 1 item.

irb(main):014:0> Post.count
   (1.3ms)  SELECT COUNT(*) FROM "posts"
=> 1

Here is an image of the empty div.


Solution

  • Even though it hasn't been saved yet, Rails is considering the @new_post to be part of current_user.posts, so you have a blank post at the end of your @posts list.

    It doesn't turn up in the database query because it hasn't been saved.

    Depending on what you need to do, you could make @new_post just an empty post (@new_post = Post.new) and assign the user when saving.

    Or in your each loop you you can check to see if the post has a body before creating the div if you can rely on that check to give you the results you want:

    <div id="post_feed">
      <%@posts.each do |p|%>
        <% if p.body %>
           <div class="post_text_box">
             <%=p.body%>
            </div>
         <%end%>
       <%end%>
     </div>
    

    You don't need the if @posts.any? check as it will always evaluate to true because of the new post created with @new_post = current_user.posts.new.

    And generally in ruby, you won't need to check if an array is empty before running an each loop because the each loop won't do anything (or throw an error) with an empty array.