Ajax / Rails嵌套注释

时间:2012-06-29 23:09:00

标签: javascript ruby-on-rails ajax

我有一个应用程序,其中book_comments属于书籍。

我的路线档案:

resources :books do
  resources :book_comments
end

我在show.html.erb上有一个book_comment表格供书籍使用。

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

我正在使用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 %>

当调用@ 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

book_comment已保存,但尝试通过_book_comments partial中的ajax渲染时出现问题:

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

via:book_comments文件夹中的create.js.erb

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

总而言之,我无法将book_comments中的create.js.erb渲染到图书展示页面。为什么book_comments文件夹中的create.js.erb不知道要查看中的对象并推断新书评论应该在div内?

我的错误讯息:

undefined method `comment' for nil:NilClass  

不要理解为什么。看到我正在将实例变量传递给注释partial。

1 个答案:

答案 0 :(得分:0)

你的部分做错了。您将未引用的值(注释)传递给未使用的变量(book_comment)。

而不是:

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

你应该这样做:

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