Rails 3 -redering partials和error“undefined local variable or method”

时间:2012-02-13 13:37:12

标签: ajax ruby-on-rails-3 view render partial

我在相册中有照片( PhotosController ),我想在每张照片上添加评论。在照片陈述中,我添加了部分用于渲染注释+表单以添加新注释。

我的问题是,当我发送带有新评论的表单时,我会收到渲染错误:

**NameError (undefined local variable or method `photo' for #<CommentsController:0x00000100ce0ad0>)**:

以下是我的代码:

视图/照片/ index.html.erb

<%= render @photos %>

视图/照片/ _photo.html.erb

<div><%=image_tag photo.photo.url(:thumb)%></div>
<div class="comments_to_photo">
  <%= render :partial => 'photos/photo_comments', :locals => { :photo => photo }%>
</div>

照片/ photo_comments

<%photo.comments.each do |cmnt|%>
  <div><%=cmnt.comment%></div>
<%end%> 

<%=form_tag comment_path, :remote => true do %>
  <div><%=text_area_tag 'comment[comment]'%></div>
  <%=submit_tag%>
<%end%>

控制器/ CommentsController

  def create
    @comment = Comment.new(params[:comment])

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
        format.js {
          render :partial => '/photos/photo_comments', :locals => { :photo => photo } do |page|; page << "$(this).html('abcde');" end  
        }
      else
        format.html { render action: "new" }
        format.js
      end
    end
  end

我想刷新照片中的表单和评论声明,其中添加了评论。请问有人可以帮助我,如何避免上述错误?

提前谢谢

编辑:我通过AJAX添加了刷新评论文件 _photo_comments.js.erb

$('#photo_comment').html("<%= escape_javascript(render('photos/photo_comments')) %>");

我收到错误

ActionView::Template::Error (stack level too deep):
  activesupport (3.2.1) lib/active_support/notifications/instrumenter.rb:23

有几十行:

  Rendered photos/_photo_comments.js.erb (562.2ms)

和最后一个

Completed 500 Internal Server Error in 580ms

渲染有什么问题?我无法从部分JS文件渲染部分html文件?

2 个答案:

答案 0 :(得分:3)

在您的控制器中,您有:

:locals => { :photo => photo }

但变量photo不存在。它应该是:

:locals => { :photo => @comment.photo }

答案 1 :(得分:0)

image_tag photo.photo.url(:thumb)&lt; - 这是您想拥有的photo.photo吗?