mardi 27 février 2018

Ruby on Rails view iterrates through object even when object is nil

I am a beginner when it comes to ROR and programming in general. I was working through the basic getting started guide in the documentation and am working on creating a comments view for a blog. I have the following code in my view to render all comments on an article -

<% @article.comments.each do |comment| %>
  <p>
    <strong>Commenter: </strong>
    <%= comment.commenter %>
  </p>
  <p>
    <strong>Comment: </strong>
    <%= comment.body %>
  </p>
<% end %>

I am having trouble understanding why this code renders the 'Commenter:' and 'Comment:' titles even when there is no comment associated with the specific article?!

I also tried wrapping the above code in -

<% if @article.comments.all.empty? == false %>
  <!--Code Above-->
<% end %>

just to experiment with it.This will prevent the titles from being rendered if there is no comments however when I add one comment, the title get rendered again in addition to the comment just added. I just need an explanation of this to better understand what is going on.

Aucun commentaire:

Enregistrer un commentaire