1

Yes, I already checked here. It didn't work.

Rails: 5.0.2 Ruby: 2.4.0

I have a collection for comments and every time it is called, it renders one time too many and an empty comment always appears below others and when no comments exist, one empty one still renders.

Here is the code:

View

<h2>Add a comment:</h2>
<%= render 'comments/form' %>

<h2>Comments</h2>
<%= render @video.comments || "There are no comments yet." %>

Form partial

<%= form_for([@video, @video.comments.new]) do |f| %>
    <p>
      <%= f.label :name %><br>
      <%= f.text_field :commenter %>
    </p>
    <p>
      <%= f.label :body %><br>
      <%= f.text_area :body %>
    </p>
    <p>
      <%= f.submit %>
    </p>
<% end %>

Comment partial

<p>
  <strong>Name:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>

<p>
  <%= link_to 'Destroy Comment', [comment.video, comment],
              method: :delete,
              data: { confirm: 'Are you sure?' } %>
</p>

Controller

def create
    @video = Video.find(params[:video_id])
    @comment = @video.comments.create(comment_params)
    redirect_to video_path(@video)
end

def destroy
    @video = Video.find(params[:video_id])
    @comment = @video.comments.find(params[:id])
    @comment.destroy
    redirect_to video_path(@video)
end

private
def comment_params
    params.require(:comment).permit(:commenter, :body)
end

Does anyone know why this would render the partial an extra time?

Community
  • 1
  • 1
Mark Kramer
  • 3,134
  • 7
  • 34
  • 52

1 Answers1

1

You may try to call .scope on comments association:

<%= render @video.comments.scope || "There are no comments yet." %>
Slava.K
  • 3,073
  • 3
  • 17
  • 28
  • This actually did work to remove the empty comment, however now when there are no comments it still doesn't output "There are no comments yet." I could make a javascript function to serve this functionality but I'd prefer not to have to. – Mark Kramer Apr 09 '17 at 15:45
  • well, it is possible to achieve this without javascript by rendering comments using `if - else` condition: <% if @video.comments.scope.any? %> etc... – Slava.K Apr 09 '17 at 18:41