[英]Ajax/Rails Nested Comments
I have an application where book_comments belongs_to books. 我有一个应用程序,其中book_comments属于books。
My routes file : 我的路线文件:
resources :books do
resources :book_comments
end
I have a book_comment form on show.html.erb for books. 我在show.html.erb上有一个book_comment表单用于书籍。
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 : 我正在使用ajax通过以下部分将book_comments发布到书展页面:_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: 调用@new_book_comment时,它指的是book_comments_controller创建动作:
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: book_comment已保存,但是尝试通过ajax在_book_comments部分中进行渲染时出现了我的问题:
<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 通过:book_comments文件夹中的create.js.erb
$("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. 总而言之,我在使book_comments中的create.js.erb呈现到书展页面时遇到麻烦。 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? 为什么book_comments文件夹中的create.js.erb不知道查看中的对象并推断新书评应该放在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). 您正在将未引用的值(注释)传递给未使用的变量(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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.