Skip to content Skip to sidebar Skip to footer

Rails 5 + Ajax: Comment Appended Only If A Comment Exists

I am trying to create a feature where users can create comments on articles with Ajax. However, i can't understand why the comment can only be successfully rendered through ajax if

Solution 1:

Try something like:

  <%= render 'comments/comment_form' %>
  <% if@comments.exists? %>
    <divclass= "comment" >
      <%= render @comments %>
    </div>
  <% else %>
    <divclass= "comment"><p> There are no comments yet.</p></div>
  <% end %>

and:

$('.comment').append("<%= escape_javascript (render partial: @comment) %>");

Because your if statement doesn't create div#comment if there are now comments, so

$('#comment').append("<%= escape_javascript (render partial: @comment) %>"); cant append anything to #comment since it doesn't exist in HTML.

Solution 2:

I believe the problem is in your create method. Since you have redirected to @comment.article, create.js.erb cannot be reached anymore. Try to rewrite the create method like this:

defcreate@comment = @article.comments.build(comment_params)
  @comment.user = current_user
  if@comment.save
    respond_to do|format|
      format.html do 
        flash[:success] = "Your comment was created successfully"end
      format.js
    endunless@comment.article.user == current_user
      Notification.create!(recipient:@article.user, actor: current_user, action:"posted", notifiable:@comment)
    endelse
    respond_to do|format|
      format.html { redirect_to @comment.article, flash[:error] = "Unable to submit comment."}
    endendend

Post a Comment for "Rails 5 + Ajax: Comment Appended Only If A Comment Exists"