【问题标题】:Rails Error submitting partial via JavascriptRails错误通过Javascript提交部分
【发布时间】:2011-03-31 23:52:58
【问题描述】:

我的控制器中有以下代码:

文件:app/controllers/photos_controller.rb

def show_snapshot_comments
    snapshot = Snapshot.find(params[:id])
    @photo = snapshot.photo
    comments = snapshot.comments.paginate :page => params[:page]
    @snapshot_comment = snapshot.comments.new
      respond_to do |format|
        format.js
      end
   end

JavaScript (jQuery): 文件:app/views/photos/show_snapshot_cmets.js.erb

$j('#info').append("<%= escape_javascript(render :partial  => "snapshot_comments",
        :locals   => {:snapshot => snapshot, :comments => comments}) %>" );

show_snapshot_copmments 从以下位置调用: app/views/photos/show.html.erb

它似乎没有工作。

我的错误:

渲染照片/show_snapshot_cmets

ActionView::TemplateError (undefined local variable or method `snapshot' for #<ActionView::Base:0x2aaaaea473c8>) on line #2 of app/views/photos/show_snapshot_comments.js.erb:
1: $j('#info').append("<%= escape_javascript(render :partial  => "snapshot_comments",
2:         :locals   => {:snapshot => snapshot, :comments => comments}) %>" );

    app/views/photos/show_snapshot_comments.js.erb:2
    app/controllers/photos_controller.rb:227:in `show_snapshot_comments'

有什么想法吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails rjs


    【解决方案1】:

    您正在尝试将局部变量传递给部分“快照_cmets”。但是,这两个局部变量快照和 cmets 未在当前范围内(在视图中)定义。

    如果您想将变量从控制器传递给视图,您必须执行以下操作:

    def show_snapshot_comments
        @snapshot = Snapshot.find(params[:id])
        @photo = snapshot.photo
        @comments = snapshot.comments.paginate :page => params[:page]
        @snapshot_comment = snapshot.comments.new
          respond_to do |format|
            format.js
          end
       end
    
    $j('#info').append("<%= escape_javascript(render :partial  => "snapshot_comments",
            :locals   => {:snapshot => @snapshot, :comments => @comments}) %>" );
    

    试试上面的代码,看看它是否有效。我只是将快照和 cmets 更改为 @snapshot 和 @cmets。

    【讨论】:

    • 错过了 cmets 位 ;)
    • 我发誓我刚刚在投票时看到了一匹带气球的马的动画。一定是水里的东西……
    • 亲爱的,是因为愚人节吗=)
    • 谢谢!!一切正常,除了我必须将 @ 添加到所有快照实例。
    【解决方案2】:

    快照在控制器中设置为局部变量,因此模板看不到它。将其设置为实例变量:

    @snapshot = Snapshot.find(params[:id])
    

    然后在模板中:

    :locals   => {:snapshot => @snapshot
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-07
      • 2021-06-22
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      相关资源
      最近更新 更多