简体   繁体   中英

Ajax/Rails Nested Comments

I have an application where book_comments belongs_to books.

My routes file :

resources :books do
  resources :book_comments
end

I have a book_comment form on show.html.erb for books.

def show
  @book = Book.find(params[:id])
  @new_book_comment = @book.book_comments.build
end

I'm using ajax to post the book_comments to the book show page via a partial: _book_comment_form.html.erb :

<%= form_for([@book, @new_book_comment], remote: :true) do |f| %>
  <div class="field" style="margin-top:60px;">
    <%= f.text_area :comment, rows: 3 %> 
    <%= f.submit "Add Comment" %>
  </div>
<% end %>

When @new_book_comment is called it refers to a book_comments_controller create action:

def create
    @book = Book.find(params[:book_id])
    @book_comment = current_user.book_comments.build(params[:book_comment]) do |f|
        f.book_id = @book.id
    end
if @book_comment.save
      respond_to do |format|
    format.html { redirect_to @book }
    format.js { render :layout => false }
  end
end

end

The book_comment is saved but my problem comes in when trying to render via ajax in the _book_comments partial:

<div id="comments">
<% @book_comments.each do |book_comment| %>
  <%= render 'comment', :book_comment => comment %>
  </div>
<% end %>
</div>

via: create.js.erb in the book_comments folder

$("div#comments").append("<%= escape_javascript(render('books/comment'))%>")

To sum, I'm having trouble making the create.js.erb in book_comments render to the book show page. Why wouldn't create.js.erb in the book_comments folder know to look at the objects in the and infer the new book comment should go inside the div?

My error message:

undefined method `comment' for nil:NilClass  

don't understnd why. Seeing that I'm passing the instance variable to the comment partial.

Your partial's doing it wrong. You're passing a not referenced value (comment) to a not used variable (book_comment).

Instead of:

<% @book_comments.each do |book_comment| %>
  <%= render 'comment', :book_comment => comment %> ....

you should do:

<% @book_comments.each do |book_comment| %>
  <%= render 'comment', :comment => book_comment  %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM