Przemek Mroczek
Przemek Mroczek

Reputation: 357

How to get this ajax to work in rails?

I am trying to get this to work, but I really can't get where the problem is. This is code. I try to render comment without refreshing page, after creating them.

create.js.erb

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

comments_controller.rb

class CommentsController < ApplicationController
def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create!(params[:comment])

    respond_to do |format|
        format.html
        format.js
    end
end
end

index.html.erb

<% @posts.each do |post| %>
    <div class="post">
        <p><strong> <%= post.title %> </strong>, posted <%= post.created_at.to_date %> </p> <br />
        <%= post.content %> <br />

        <%= simple_form_for [post, post.comments.build], :remote => true do |f| %>
            <%= f.input :content %>
            <%= f.button :submit %>
        <% end %>


        <% post.comments.each_with_index do |comment, i| %>
            <p> <%=i + 1%>.<%= comment.content %></p>
        <% end %>

    </div>

<% end %>

<p><%= link_to "New Post", new_post_path %></p> 

Upvotes: 1

Views: 77

Answers (1)

coletrain
coletrain

Reputation: 2849

Install firebug for firefox so you can debug your ajax and js code. I usually use it when adding ajax to my application to make sure there are not any errors.

Upvotes: 1

Related Questions