0

I'm new to programming and have been learning Ruby on Rails for about 6 weeks. I've added commenting functionality to my app, and while comments are being displayed properly, so is everything else in the (sqlite3) database associated with the comment - created_at, updated_at, comment_id, post_id. The partial that displays comments has the following code:

<%= form_for [post, comment] do |f| %>
  <p><%= @comments.each do |comment| %></p>
  <small>
  <p><%= comment.body %></p>
  </small>
  <% end %> 
<% end %>

As you can see, I'm only trying to display the comment body, but I'm displaying everything.

Here is the create method from the comments controller:

def create  
   @post =  Post.find(params[:post_id])
   @comment = current_user.comments.build(params_comment)
   @comment.post = @post
   authorize @comment

   if @comment.save
     flash[:notice] = "Comment was created"
     redirect_to [@post.topic, @post]
   else 
     flash[:error] = "Comment failed to save"
     redirect_to [@post.topic, @post]
   end
  end
end

I'm not sure why everyting is displaying if I'm only calling .body on comment. I've researched this problem but haven't found anything. Any help would be appreciated.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
EricLowber
  • 133
  • 2
  • 12

1 Answers1

1

Here is the fix :-

<%= form_for [post, comment] do |f| %>
  <!-- Here I removed `=` from `<%` %> -->
  <p><% @comments.each do |comment| %></p> 
  <small>
  <p><%= comment.body %></p>
  </small>
  <% end %> 
<% end %>

#each returns the collection when the block is finished with full iteration. Now, you used <%= ..%>, which then printing the return value of #each. But if <%..%>, it wouldn't print although the @comments.each still returning the @comments collection.

Pavan
  • 81
  • 3
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • [`erb` commenting](http://stackoverflow.com/questions/2774841/best-way-to-add-comments-in-erb) is not working. Anybody, if know how to do, please edit my answer. – Arup Rakshit Nov 02 '14 at 14:18