0

So I'm trying to update my comments section with AJAX without the full page refresh for a college project. However I can't seem to get this working. In the console it gives me s

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

My show.html.erb file:

<h1>Title: <%= @post.title %></h1>
<h2>Body: <%= @post.body %></h2>
<hr />
<h1>Your comments</h1>
<%= link_to "View comments", "#", id: "comments-link" %>
<ol id="comments">
    <%= render 'comments' %>
<hr />
<h1>Create comment</h1>

    <%= form_for(@comment, :html => {class: "form", role: "forms"}, :url => post_comments_path(@post), remote: true)  do |comm| %>
<div class="container">
    <div class="input-group input-group-md">
            <%= comm.label :body %>
            <%= comm.text_area :body, class: "form-control", placeholder: "Enter a comment" %>
    </div>
                <%= comm.submit "custom", id: "button" %>
    </div>
<% end %>
</ol>

My comments.coffee:

$(document).on "page:change", ->
  $('#comments-link').click ->
    $('#comments').fadeToggle()
    $('#comments_body').focus()

My create.js.erb:

$('#comments').append("<%= j render @comment  %>");

and my Comments controller:

class CommentsController < ApplicationController

def index

end

def new
end

def new
    @comment = Comment.new
end

def create
    @comment = Comment.new(comment_params)
    @comment.post_id = params[:post_id]
    if @comment.save
        flash[:success] = "Successfully created comment"
        respond_to do |format|
            format.html { redirect_to post_path(@comment.post_id) }
            format.js
        end
    else
        flash[:danger] = "Failed to create comment"
        redirect_to root_path
    end
end

private

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

I may have missed some files so just let me know, it is basic as it's just a post and comment system - no styling needed for the project, so yeah. I have been trying this for the last 4 hours and other places just don't work. I've looked on here, Youtube - everywhere however no one else's code works for me so I have come here! Thank's for you're help.

EDIT:

I noticed it said to create a view in the error response, however I made that view and rendered the comment's body onto the create.html.erb however I just need to display the form now.

6
  • check console for error..and please post your error here. With 500 it must be giving some more error logs.. Commented Dec 2, 2015 at 15:29
  • I literally just updated that :) Commented Dec 2, 2015 at 15:30
  • in this for remote you should create create.js.erb instead create.html.erb Commented Dec 2, 2015 at 15:33
  • railscasts.com/episodes/136-jquery Commented Dec 2, 2015 at 15:34
  • I have a create.js.erb but it wanted me to make a create.html.erb as well Commented Dec 2, 2015 at 15:37

1 Answer 1

2

I notice you are posting to the url post_comments_path(@post). For nested routes, it might be cleaner to do the following:

1) Post to the nested route directly:

<%= form_for([@post, @comment], html: {class: "form", role: "forms"}, remote: true)  do |comm| %>

2) Make sure your routes are nested properly, in routes.rb:

resources :posts do
  resources :comments
end

3) Refactor your CommentsController, to build through the @post instance:

class CommentsController < ApplicationController

  before_action :get_post

  def index
    @comments = @post.comments
  end

  def new
    @comment = @post.comments.build      
  end

  def create
    @comment = @post.comments.build(comment_params)

    if @comment.save

      flash[:success] = "Successfully created comment"

      respond_to do |format|
        format.html { redirect_to post_path(@post) }
        format.js
      end

    else
      respond_to do |format|
        format.html { render :new }
        format.js { render :error }
      end      
    end
  end

  private

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

  def get_post
    @post = Post.find(params[:post_id])
  end  

end

4) Render the validation errors in app/views/comments/error.js.erb. I'll let you decide how best to do that, but here's a quick dump to the console:

<% @comment.errors.full_messages.each do |message| %>
  console.log("<%= message %>");
<% end %>

This file is not to be confused with your app/views/comments/create.js.erb which is handling successful save of the comment. That should look something like this:

$('#comments').append("<%= j render @comment %>"); 
$(".form")[0].reset();

5) Tweak your view a little bit. I notice you need to output the comments differently:

<ol id="comments">
    <%= render @post.comments %>
</ol>

which should correspond to a partial in app/views/comments/_comment.html.erb so make sure this is there.

Sign up to request clarification or add additional context in comments.

8 Comments

I have done all of this and none of it seemed to work
What is the 500 error you are getting, specifically.... Can you look at the output log of your rails server and see the exact error? i.e, not the error message in the Javascript console.
'Missing template comments/create, application/create with {:locale=> [:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/adam/Desktop/ruby/rails/AJAXC/app/views" <div id="console" data-remote- path='console/repl_sessions/5e7696b1ed6d46709ba46d6d013d6240' data-initial-prompt='>> '>' </div> This is the error I am getting
It is - this ones asking for the create.html.erb for some reason. It shouldn't need a template right? It's looking for the action - but on top off this if I refresh the page it still displays the comment it said it can't make.
Your remote: true should mean the form submits with the js format, and the respond_to block should handle that accordingly. Provided you have //= require jquery_ujs in your application.js manifest
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.