ruby-on-rails-3jquerycommentsremotipart

Do I need to reload the comment object or the partial that contains the comment in case of using Ajax in Rails 3?


I have been trying to figure out adding comments without reloading the page using Ajax, after reading few different tutorials this is what I came up to so far, and it's not working:

inside user_comments/_comments.html.erb

    <div id="comment_form">
  <%= simple_form_for [@commentable, @comment], :html => { :multipart => true }, :remote => true do |f| %>
    <div class="picture"><%= image_tag current_user.avatar.url(:thumb) %></div>
    <%= f.input :content, label: false, :placeholder => "Add Comment", :input_html => { :rows => 4 } %>
    <%= f.submit "Add Comment" %>
  <% end %>
   </div>

Inside the controller:

def create
@users = User.all
@comment = @commentable.user_comments.new(params[:user_comment])
@comment.user_id = current_user[:id]
#@commentable.user_comments.create(:user_id => current_user[:id])
if @comment.save

  flash[:notice] = "Successfully created comment."
  respond_to do |format|
    format.html { redirect_to @commentable }
    format.js
    #format.js #{ render 'create.js.erb' }
    end
else
  render :new
end
 end

and inside the create.js.erb

// Display a Javascript alert
<% if remotipart_submitted? %>
    $("#comments_list").append("<%= escape_javascript(render(:partial => 'user_comments/comments')) %>");
<% end %>

I'm using a Gem called: remotipart

I don't know what I'm missing in the process. in the console I get:

POST http://localhost:3000/assignments/2/user_comments

200 OK
        134ms

which means the post goes through, but the comment doesnt get added back to the partial.


Solution

  • Ok after 2 days! I fixed it, here is what I can share and might help:

    1- make sure to include the :remote => true to the form that is about to be submitted 2- Check the controller and see what the Create action is being redirected, in my case I changed to this:

    def create
    @users = User.all
    @comment = @commentable.user_comments.new(params[:user_comment])
    @comment.user_id = current_user[:id]
    #@commentable.user_comments.create(:user_id => current_user[:id])
    if @comment.save
      flash[:notice] = "Successfully created comment."
      respond_to do |format|
        format.html
        format.js   {@comments = @commentable.user_comments}
    
    
        end
    else
      render :new
    end
    end
    

    Then make sure the create.js.erb is written properly:

        $("#comments_list").empty()
    $("#comments_list").append("<%= escape_javascript(render(:partial => 'comments')) %>");
    

    there you go! I hope some creates a proper tutorial for newbies like me :)!