【问题标题】:Rails 3 -rendering partials and error "undefined local variable or method"Rails 3 - 渲染部分和错误“未定义的局部变量或方法”
【发布时间】:2012-03-04 21:53:42
【问题描述】:

我在画廊 (PhotosController) 中有一张照片,我想为每张照片添加一个 cmets。在照片声明中,我添加了用于渲染 cmets 的部分内容 + 用于添加新评论的表单。

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

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

这是我的代码的外观:

views/photos/index.html.erb

<%= render @photos %>

views/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_cmets

<%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%>

控制器/评论控制器

  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

我想刷新照片中的表格和 cmets 声明,其中添加了评论。谁能帮帮我,如何避免上述错误?

提前谢谢你

编辑:我为通过 AJAX 刷新 cmets 添加了文件 _photo_cmets.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 文件?

【问题讨论】:

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


    【解决方案1】:

    image_tag photo.photo.url(:thumb) photo.photo 吗?

    【讨论】:

    • 是的,因为我在表 Photos 中有列 photo_file_namephoto_content_type - 这是正确的,图像显示正确,但是当我想通过 AJAX 渲染部分时,我收到上面的错误...
    【解决方案2】:

    在您的控制器中,您有:

    :locals => { :photo => photo }
    

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

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

    【讨论】:

    • 谢谢,这解决了我的问题。我试图通过 AJAX 渲染 cmets 的语句,但我收到错误“堆栈级别太深” - 你知道吗,我可能忘记了什么? (我更新了我的问题)。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2014-08-15
    • 2016-11-21
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多